﻿//*************************************************************************
//面向服务的协作式智能交通系统仿真软件SoC-ITSS v2.1 alpha
//发布单位：西北工业大学--巴黎高科MINES机器人与群智能系统联合实验室
//团队负责人：张凯龙 Zhang Kailong
//团队成员：张大方、杨安胜、王敏、谢策、王雨佳、谢尘玉等
//联系我们：kl.zhang@nwpu.edu.cn
//2012-2021
//*************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using CyberCarSimulation.Bean;
using CyberCarSimulation.RoadModel;
using CyberCarSimulation.Regulation;
using CyberCarSimulation.Simulation;

//*******************************************************
//
//文件名(File Name):           PriorSingleQueueSingleVehicle_Sche.cs
//
//数据表(Tables):              nothing 
//
//          修改理由：         基于车道优先级 HWFP-SQ-SV
//
//*******************************************************

namespace CyberCarSimulation.Algorithm
{
    //SuperVehicleManager对象描述了一辆车在通过路口的过程中对S-CS资源的全部需求
    //每个SuperVehicleManager对象中包含若干个VehicleManger对象，
    class PriorSingleQueueSingleVehicle_Sche
    {

        private string ID;        //Agent的ID,此ID与路口ID相同
        private int IDNum;        //第几个Agent的Num号
        private int MaxAuthNum;     //最大授权
        private int MsgCount = 0;   //发送至车辆的消息数量

        /************************************************************************/
        /* 发出申请消息之后的车辆的数据信息                                                                     */
        /************************************************************************/
        //键值对，用于存储申请该临界区的车辆的VehicleManager信息，取用方式为<车辆的ID，车辆对应的CS消息>，其中每一条队列既是一个临界区所对应的CS消息
        private List<KeyValuePair<string, VehicleManager>>[] CS = new List<KeyValuePair<string, VehicleManager>>[5];
        //各车道的队列，存储各车道申请临界区的车辆的SuperVehicleManager信息，对应于4个车道
        private List<SuperVehicleManager>[] LaneQueue = new List<SuperVehicleManager>[5];

        /************************************************************************/
        /* 当前已授权车辆的信息，此处只存储其车辆和临界区消息，不存储具体的消息  */
        /************************************************************************/
        //键值对，<CSID，ID>用于记录将编号为CSID的S-CS资源授权给编号为ID的车辆,其数目最多为4 ，对应于4个临界区
        public Dictionary<int, List<string>> Authorize_CS_to_Vehicle = new Dictionary<int, List<string>>();
        //保存当前被授权的车辆ID号，  其数量最多为4，代表一个时间段之内最多只有4辆车被授权
        private List<string> Authorized_Vehicle_Sequence = new List<string>();
        //保存之前已经被授权完成的车辆这些车辆无需再被授权
        private List<string> Already_Authorized_All_CS_Vehicles = new List<string>();

        //Token[XXX]为true表示编号为XXX的S-CS资源已经被占用，为false则表示该资源空闲
        private int[] Token = new int[5];

        //用于分辨是否会产生死锁
        private bool[] Walked = new bool[5];
        private bool[,] SourceGraph = new bool[5, 5];

        //用于多车授权时，标记 N辆车所需要的临界区   false代表不需要 true代表需要
        private bool[] IsAuth = new bool[5];


        //为true表示当前发出预约请求的车辆中没有高优先级车辆，为false则相反。该变量用于控制调度算法切换。
        private bool isAllLowPrior = true;
        //标志出现的优先车辆是高优先级车辆还是中优先级车辆，其中Definitions.Prio_High表示高优先级车辆，Definitions.Prio_Mid表示中优先级车辆
        private int PriorType = Definitions.Prio_High;
        //Weight[1]表示道路1的权重系数
        private float[] Weight = new float[5];
        //DelayTime[1]表示道路1的延迟时间
        private float[] DelayTime = new float[5];
        //<ID，SVM>将编号为ID的车辆与对应的SuperVehicleManager对象SVM关联起来，同时也是调度器中的全局队列，存储全部车辆对S-CS资源的需求信息
        private Dictionary<string, SuperVehicleManager> VehicleMng = new Dictionary<string, SuperVehicleManager>();
        //原高优先级车辆，其中float为到达下一个临界区的时间，但是尽量不做排序
        private List<string> HighPriorVehicleOrigin = new List<string>();
        //当前原高优先级车辆所处的车道
        private List<int> HighPriorLaneIDOrigin = new List<int>();

        float Time = 0;  //用于记录 主干道车辆多车授权时，最后一个车辆离开它所需要的最后一个临界区
        float StartTime = 0;//用于记录 主干道车辆多车授权时，最后一个车辆进入它所需要的第一个临界区
        bool IsPass = false; //用于记录主干道车辆多车授权时，最后一个车辆的 最后一个临界区是否已经通过 true为通过， false为没通过
        private SuperVehicleManager SVMP = null; //用于记录主干道车辆多车授权时，最后一个车辆
        public static int AuthNum = 0; //当前多车授权的车辆的个数
              

        /************************************************************************/
        /* 初始化                                                                     */
        /************************************************************************/
        public PriorSingleQueueSingleVehicle_Sche(string ID)
        {
            //设置ID
            this.ID = ID;
            this.IDNum = int.Parse(ID.Substring(3, 2));

            for (int i = 0; i < 5; i++)
            {
                this.Token[i] = 0;   //为false则表示该临界区资源空闲
                this.CS[i] = new List<KeyValuePair<string, VehicleManager>>();
                this.LaneQueue[i] = new List<SuperVehicleManager>();
                this.IsAuth[i] = false;
                this.Weight[i] = 0;
            }
        }

        /************************************************************************/
        /* MultiSCSFIFO_Sche对象的对外接口，用于执行FIFO调度算法                */
        /************************************************************************/
        public void executeAlgorithm(Intersection Intersection,int AuthMax)
        {
            this.MaxAuthNum = AuthMax * 4;

            //读入消息
            this.readMessageFromVehicle(Intersection);
            //判断是否存在高优先级车辆以及中优先级的车辆
            this.isAllLowPrior = this.isPriorVehiOccur();
            //测试优先级是否合理
            //this.testPrior();

            //对临界区进行分配
            //this.processLeftVehicles();
            if (this.isAllLowPrior == true)//if (this.PriorType == Definitions.Prio_High)
            {
                this.OriginalHighPriorVehicleQueueCreate(this.PriorType);
                this.executeAlgorithmPrior(Intersection);
            }
            else
            {
                this.executeAlgorithmFIFO(Intersection);
            }

            for (int i = 0; i < 5; ++i)
            {
                for (int j = 0; j < this.CS[i].Count; ++j)
                {
                    this.CS[i].ElementAt(j).Value.isSelect = false;
                }
            }
        }

        /************************************************************************/
        /* 从Msg_Buffer类的存储空间中读取相关信息，如Msg_Reservation消息、Msg_Release消息等。*/
        /************************************************************************/
        private void readMessageFromVehicle(Intersection Intersection)
        {

            //获取路口中的消息队列
            List<Message> VtoA_BufferTemp = Intersection.GetVtoA_Buffer();    //局部变量，需要重新写回去


            while (VtoA_BufferTemp.Count != 0)
            {

                //取出一条Message
                Message m = VtoA_BufferTemp.ElementAt(0);
                VtoA_BufferTemp.Remove(m);

                switch (m.GetType())
                {
                    //在预约消息下需要创建新消息，并将消息存入不同的队列中
                    case Definitions.MsgReservation:

                        SuperVehicleManager vm;
                        string LaneIDTemp = m.GetLaneIDStr();

                        vm = new SuperVehicleManager(m.GetSender(), int.Parse(LaneIDTemp.Substring(5, 1)), m.GetTsArray(), m.GetTeArray(),
                                            m.GetTotal_Dis(), m.GetSectionID(), m.GetPriority());



                        /*将生成的车辆管理实体加入到对应的队列中*/
                        //因为进入车道的车辆本身具有具有顺序，所以此处无需对车道按照车辆插入时间对车辆进行排序
                        this.LaneQueue[vm.LaneID].Add(vm);
                        this.updateCSQueue(vm);
                        this.sortCSQueue();
                        break;
                    case Definitions.MsgFault:              //车辆故障信息
                        break;
                    case Definitions.MsgWait:               //等待临界区消息
                        break;
                    case Definitions.MsgRenew:             //更新状态消息
                        //主要用于更新车辆到达时间
                        string str = m.GetLaneIDStr();
                        string section = m.GetSectionID();
                        float[] ts = m.GetTsArray();
                        float[] te = m.GetTeArray();
                        for (int i = 0; i < this.LaneQueue[int.Parse(str[5].ToString())].Count(); ++i)
                        {
                            if (this.LaneQueue[int.Parse(str[5].ToString())].ElementAt(i).getID() == m.GetSender())
                            {
                                this.LaneQueue[int.Parse(str[5].ToString())].ElementAt(i).setTs(m.GetTsArray());
                                this.LaneQueue[int.Parse(str[5].ToString())].ElementAt(i).setTe(m.GetTeArray());
                                SuperVehicleManager stmp = this.LaneQueue[int.Parse(str[5].ToString())].ElementAt(i);

                                for (int j = 0; j < section.Length; j++)
                                {
                                    if (stmp.VehicleManagers[int.Parse(section[j].ToString())] != null)
                                    {
                                        stmp.VehicleManagers[int.Parse(section[j].ToString())].setTs(ts[j]);
                                        stmp.VehicleManagers[int.Parse(section[j].ToString())].setTe(te[j]);
                                    }
                                }
                            }
                        }

                        for (int j = 0; j < section.Length; j++)
                        {
                            foreach (KeyValuePair<string, VehicleManager> kvp in this.CS[int.Parse(section[j].ToString())])
                            {
                                if (kvp.Key == m.GetSender())
                                {
                                    kvp.Value.setTs(ts[j + 1]);
                                    kvp.Value.setTe(te[j + 1]);
                                }
                            }
                        }
                        this.sortCSQueue();
                        break;
                    case Definitions.MsgRelease:                //离开临界区消息
                        /*释放对应的SCS*/
                        //将对应的临界区的消息去除
                        str = m.GetSender();

                        Vehicle VehicleTemp = FindVehicleByID(str);
                        string Lanestr = VehicleTemp.Get_Previous_LaneID();

                        //CS信息，若释放，则删除对应的临界区
                        foreach (KeyValuePair<string, VehicleManager> kvp in this.CS[int.Parse(m.GetSectionID().ToString())])
                        {
                            if (kvp.Key == m.GetSender())
                            {
                                this.CS[int.Parse(m.GetSectionID().ToString())].Remove(kvp);
                                break;
                            }
                        }

                        //LaneQueue信息，若释放，则将对应的临界区的token信息，left信息更新，其中HaveTokenCount因为其已被申请过，所以不作修改
                        for (int i = 0; i < this.LaneQueue[int.Parse(Lanestr[5].ToString())].Count(); ++i)
                        {
                            if (this.LaneQueue[int.Parse(Lanestr[5].ToString())].ElementAt(i).getID() == m.GetSender())
                            {
                                this.LaneQueue[int.Parse(Lanestr[5].ToString())].ElementAt(i).Token[int.Parse(m.GetSectionID().ToString())] = false;
                                this.LaneQueue[int.Parse(Lanestr[5].ToString())].ElementAt(i).Left[int.Parse(m.GetSectionID().ToString())] = true;
                            }
                        }

                        //将被占用临界区标志位为未被占用
                        this.Token[int.Parse(m.GetSectionID().ToString())]--;
                        if (Token[int.Parse(m.GetSectionID().ToString())] == 0)
                        {
                            IsAuth[int.Parse(m.GetSectionID().ToString())] = false;
                        }
                        //IsAuth[int.Parse(m.getSectionID().ToString())] = false;

                        for (int i = 0; i < Authorize_CS_to_Vehicle.Count; i++)
                        {
                            List<string> ltmp = Authorize_CS_to_Vehicle[int.Parse(m.GetSectionID().ToString())];
                            foreach (string stmp in ltmp)
                            {
                                if (str == stmp)
                                {
                                    this.Authorize_CS_to_Vehicle[int.Parse(m.GetSectionID().ToString())].Remove(stmp);
                                    break;
                                }
                            }
                            if (this.Authorize_CS_to_Vehicle[int.Parse(m.GetSectionID().ToString())].Count == 0)
                            {
                                this.Authorize_CS_to_Vehicle.Remove(int.Parse(m.GetSectionID().ToString()));
                                break;
                            }

                        }
                        this.OutPutAuthMsg(2, m);
                        break;
                    case Definitions.MsgPassing:
                        //标志车辆正在经过某临界区，无需处理
                        break;
                    case Definitions.MsgPassed:
                        //车辆离开十字路口
                        this.removePassedVehicle(m.GetSender());
                        break;
                    default:
                        System.Windows.Forms.MessageBox.Show("Error FWFP-SQ-SV ");
                        break;
                }
            }

            //将数据写会MainData中
            Intersection.SetVtoA_Buffer(VtoA_BufferTemp);
            MainData.UpdateIntersectionList(Intersection);
        }

        /************************************************************************/
        /* 更新个临界区的消息队列                                                                     */
        /************************************************************************/
        private void updateCSQueue(SuperVehicleManager svm)
        {
            //将SuperVehicleManger分析成多个VehicleManger
            //将VehicleManger放入CS中
            for (int i = 1; i < 5; i++)
            {
                if (svm.VehicleManagers[i] != null)
                {
                    VehicleManager vm = svm.VehicleManagers[i];           //VehicleManagers[i]用于存储不同临界区的预约消息
                    VehicleManager vm2 = new VehicleManager(vm.getID(), vm.getLaneID(), vm.getTs(), vm.getTe(),
                        vm.getCurrent_Dis(), vm.getSectionIDs(), vm.getOriginalPriority(), true);
                    vm2.setCSCount(svm.VehicleManagers[i].getCSCount());

                    //更新临界区的消息队列
                    KeyValuePair<string, VehicleManager> kvp = new KeyValuePair<string, VehicleManager>(vm2.getID(), vm2);
                    this.CS[int.Parse(vm2.getSectionIDs())].Add(kvp);
                }
            }
        }

        /************************************************************************/
        /* 将各临界区的申请车辆按照到达时间的先后顺序进行排序                                                                     */
        /************************************************************************/
        private void sortCSQueue()
        {
            for (int i = 1; i < 5; i++)
            {
                if (this.CS[i].Count != 0)
                {
                    for (int j = 0; j < this.CS[i].Count; j++)
                    {
                        for (int k = j + 1; k < this.CS[i].Count; k++)
                        {
                            if (this.CS[i].ElementAt(j).Value.getTs() > this.CS[i].ElementAt(k).Value.getTs())
                            {
                                KeyValuePair<string, VehicleManager> kvp;  //前面车辆的到达时间大于后面车辆的到达时间，两调换顺序
                                kvp = this.CS[i].ElementAt(j);
                                this.CS[i][j] = this.CS[i].ElementAt(k);
                                this.CS[i][k] = kvp;
                            }
                        }
                    }
                }
            }
        }

        /************************************************************************/
        /* 将过了临界区的车辆删除，并释放占用的资源,
         * ID为车辆的编号                                                                     */
        /************************************************************************/
        private void removePassedVehicle(string ID)
        {
            Vehicle VehicleTemp = FindVehicleByID(ID);
            string LaneIDPrevious = VehicleTemp.Get_Previous_LaneID(); //车辆之前所在的车道序号

            int LaneID = int.Parse(LaneIDPrevious[5].ToString());
            if (this.LaneQueue[LaneID].Count == 0)
            {
                return;
            }

            //删除车道车辆列表中的车辆
            foreach (SuperVehicleManager stmp in LaneQueue[LaneID])
            {
                if (stmp.ID == ID)
                {
                    this.LaneQueue[LaneID].Remove(stmp);
                    break;
                }
            }

            //将申请过临界区的车辆释放
            for (int i = 1; i < 5; i++)
            {
                foreach (KeyValuePair<string, VehicleManager> kvp in this.CS[i])
                {
                    if (kvp.Key == ID)
                    {
                        this.CS[i].Remove(kvp);
                        break;
                    }
                }
            }
            //将授权过的的车辆释放
            for (int i = 0; i < Authorized_Vehicle_Sequence.Count; ++i)
            {
                if (this.Authorized_Vehicle_Sequence.ElementAt(i) == ID)
                {
                    this.Authorized_Vehicle_Sequence.RemoveAt(i);
                }
            }
            //将授权过的临界区的释放
            for (int i = 1; i < 5; i++)
            {
                if (this.Authorize_CS_to_Vehicle.ContainsKey(i) == true)
                {
                    foreach (string stmp in Authorize_CS_to_Vehicle[i])
                    {
                        if (stmp == ID)
                        {
                            this.Authorize_CS_to_Vehicle[i].Remove(stmp);
                            break;
                        }
                    }
                }
            }
            return;
        }


        private void processLeftVehicles(Intersection Intersection)
        {
            try
            {
                string s = null;
                int CSID = 0;
                string ID = null;
                AuthNum = this.MaxAuthNum / 4;

                s = null;
                if (!IsCSEmpty())           //判断各临界区的申请队列是否为空 ,
                {
                    //若存在临界区未被占用
                    SuperVehicleManager svmp = null;
                    while (this.Token[1] == 0 && this.Token[2] == 0 && this.Token[3] == 0 && this.Token[4] == 0)
                    {
                        IsPass = false;
                        Authorize_CS_to_Vehicle.Clear();
                        svmp = this.GetArriveFirstSCSCar(Intersection);
                        if (svmp == null)
                        {
                            break;
                        }
                        SVMP = svmp;
                        //被选中车辆的ID
                        ID = svmp.getID();

                        //找到车辆Vehicle对象的LaneID                        
                        string LaneID = FindVehicleByID(ID).Get_Current_LaneID();

                        //被选中车辆的CSID 
                        CSID = int.Parse(svmp.SectionID.ElementAt(0).ToString());

                        for (int k = 1; k <= this.MaxAuthNum / 4; k++)
                        {
                            if (k == 1)
                            {
                                if (ID != null
                                           && (this.isTokenSequenceIllegal(int.Parse(LaneID[5].ToString()), ID, CSID, ref s) == false)
                                           && (this.isFirstVehicleInLane(int.Parse(LaneID[5].ToString()), ID, CSID) == true))
                                {
                                    for (int i = 1; i <= svmp.CS_Count; i++)
                                    {
                                        CSID = int.Parse(svmp.SectionID.ElementAt(i - 1).ToString());

                                        //test
                                        if (this.Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                        {
                                            Debug.WriteLine("错误啦1！");
                                        }
                                        //test finish

                                        if (this.Authorize_CS_to_Vehicle.Keys.Contains(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())))      //将车辆的CSID和ID添加到 Authorize_CS_to_Vehicle
                                        {

                                        }
                                        else
                                        {
                                            //
                                            this.Authorize_CS_to_Vehicle.Add(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()), null);
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())] = new List<string>();     //可以值是null，用的时候在实例化。
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                        }


                                        if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)   //不会死锁
                                        {
                                            this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()), Intersection);
                                            IsAuth[CSID] = true;
                                            this.setToken(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()), ID);

                                            Debug.WriteLine("HWFP-SQ-SV" + "\t" + "无HM" + "\t" + this.MaxAuthNum / 4);
                                        }
                                        else    //会产生死锁   第一辆车不授权，后面的车辆更不授权。
                                        {
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Remove(ID);
                                            //如果SCID所对应的 list的数量为0，说明 此临界区对应的队列 为空。没有车辆了 
                                            if (this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Count == 0)
                                            {
                                                this.Authorize_CS_to_Vehicle.Remove(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()));
                                                break;
                                            }
                                            break;
                                        }
                                        Time = svmp.Te[svmp.CS_Count];
                                        StartTime = svmp.Ts[1];

                                    }


                                    //判断当前被授权车辆是否还有未申请的临界区
                                    SuperVehicleManager stmp = null;
                                    int kkkk = 0;
                                    for (int i1 = 1; i1 < 5; ++i1)
                                    {
                                        for (int j = 0; j < this.LaneQueue[i1].Count; ++j)
                                        {
                                            if (this.LaneQueue[i1].ElementAt(j).ID == ID)
                                            {
                                                stmp = this.LaneQueue[i1].ElementAt(j);
                                                for (kkkk = 0; kkkk < stmp.CS_Count; kkkk++)
                                                {
                                                    if (stmp.Token[int.Parse(stmp.SectionID[kkkk].ToString())] == false)
                                                    {
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    //若车辆未申请完成所有临界区，则将其存入Authorized_Vehicle_Sequence中，作为当前仍需申请临界区的车辆对待
                                    if (kkkk != svmp.CS_Count)
                                    {
                                        if (stmp != null)
                                        {
                                            bool mark = false;
                                            for (int k1 = 0; k1 < this.Authorized_Vehicle_Sequence.Count; k1++)
                                            {
                                                if (this.Authorized_Vehicle_Sequence[k1] == stmp.ID)
                                                {
                                                    mark = true;
                                                }
                                            }
                                            if (mark == false)
                                            {
                                                this.Authorized_Vehicle_Sequence.Add(stmp.ID);
                                            }
                                        }
                                    }
                                    else
                                    {//该车辆已经申请完成所有的临界区，无需再次判断

                                        bool mark = false;
                                        for (int k1 = 0; k1 < this.Authorized_Vehicle_Sequence.Count; k1++)
                                        {
                                            if (this.Authorized_Vehicle_Sequence[k1] == stmp.ID)
                                            {
                                                mark = true;
                                            }
                                        }
                                        if (mark == false)
                                        {
                                            this.Authorized_Vehicle_Sequence.Add(stmp.ID);
                                        }
                                        this.Already_Authorized_All_CS_Vehicles.Add(stmp.ID);

                                    }
                                }

                            }
                            else            // k!=1 , 后面的车辆
                            {

                                string ID0 = ID;

                                //被选中车辆的ID
                                Vehicle vetemp = CarInLaneNext(ID0);
                                ID = vetemp.Get_ID();
                                LaneID = FindVehicleByID(ID).Get_Current_LaneID();


                                if (ID != ID0)
                                {
                                    //continue;
                                }
                                else
                                {
                                    break;
                                }

                                SuperVehicleManager svmplater = null;
                                for (int i = 1; i <= 4; i++)
                                {
                                    foreach (SuperVehicleManager svmpl in LaneQueue[i])
                                    {
                                        if (ID == svmpl.getID())
                                        {
                                            svmplater = svmpl;
                                        }
                                    }
                                }

                                CSID = int.Parse(svmplater.SectionID.ElementAt(0).ToString());

                                if (ID != null
                                        && (this.isTokenSequenceIllegal(int.Parse(LaneID[5].ToString()), ID, CSID, ref s) == false))
                                // && (this.isFirstVehicleInLane(int.Parse(ID[0].ToString()), ID, CSID) == true))
                                {

                                    for (int i = 1; i <= svmplater.CS_Count; i++)
                                    {
                                        CSID = int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString());

                                        if (this.Authorize_CS_to_Vehicle.Keys.Contains(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())))      //将车辆的CSID和ID添加到 Authorize_CS_to_Vehicle
                                        {
                                            if (!Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Contains(ID))
                                            {
                                                this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                            }

                                            //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                            //xc
                                            Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                            string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                            int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                            int temp = int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString());
                                            Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[temp].ElementAt(0));
                                            string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                            int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());
                                            

                                            if (LaneIDtemp1 != LaneIDtemp2)
                                            {
                                                this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Remove(ID);
                                            }

                                            ////如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                            //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].ElementAt(0).ElementAt(0))
                                            //{
                                            //    this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Remove(ID);
                                            //}
                                            //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[temp].ElementAt(0).ElementAt(0))
                                            //{
                                            //    this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Remove(ID);
                                            //}

                                        }
                                        else
                                        {
                                            //
                                            this.Authorize_CS_to_Vehicle.Add(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()), null);
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())] = new List<string>();     //可以值是null，用的时候在实例化。
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                        }

                                        if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)   //不会死锁
                                        {
                                            this.sendMessage(Definitions.MsgAuthorize, ID, svmplater.Original_Priority, int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()),Intersection);
                                            IsAuth[CSID] = true;
                                            this.setToken(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()), ID);
                                        }
                                        else    //会产生死锁   第一辆车不授权，后面的车辆更不授权。
                                        {
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Remove(ID);

                                            if (this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Count == 0)
                                            {
                                                this.Authorize_CS_to_Vehicle.Remove(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()));
                                                break;
                                            }
                                            break;
                                        }
                                        Time = svmplater.Te[svmplater.CS_Count];
                                        StartTime = svmplater.Ts[1];
                                        SVMP = svmplater;
                                    }


                                    //判断当前被授权车辆是否还有未申请的临界区
                                    SuperVehicleManager stmp = null;
                                    int kkkk = 0;
                                    for (int i1 = 1; i1 < 5; ++i1)
                                    {
                                        for (int j = 0; j < this.LaneQueue[i1].Count; ++j)
                                        {
                                            if (this.LaneQueue[i1].ElementAt(j).ID == ID)
                                            {
                                                stmp = this.LaneQueue[i1].ElementAt(j);
                                                for (kkkk = 0; kkkk < stmp.CS_Count; kkkk++)
                                                {
                                                    if (stmp.Token[int.Parse(stmp.SectionID[kkkk].ToString())] == false)
                                                    {
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    //若车辆未申请完成所有临界区，则将其存入Authorized_Vehicle_Sequence中，作为当前仍需申请临界区的车辆对待
                                    if (kkkk != svmplater.CS_Count)
                                    {
                                        if (stmp != null)
                                        {
                                            bool mark = false;
                                            for (int k1 = 0; k1 < this.Authorized_Vehicle_Sequence.Count; k1++)
                                            {
                                                if (this.Authorized_Vehicle_Sequence[k1] == stmp.ID)
                                                {
                                                    mark = true;
                                                }
                                            }
                                            if (mark == false)
                                            {
                                                this.Authorized_Vehicle_Sequence.Add(stmp.ID);
                                            }
                                        }
                                    }
                                    else
                                    {//该车辆已经申请完成所有的临界区，无需再次判断

                                        bool mark = false;
                                        for (int k1 = 0; k1 < this.Authorized_Vehicle_Sequence.Count; k1++)
                                        {
                                            if (this.Authorized_Vehicle_Sequence[k1] == stmp.ID)
                                            {
                                                mark = true;
                                            }
                                        }
                                        if (mark == false)
                                        {
                                            this.Authorized_Vehicle_Sequence.Add(stmp.ID);
                                        }
                                        this.Already_Authorized_All_CS_Vehicles.Add(stmp.ID);

                                    }
                                }

                            }

                        }



                    }

                    if (SVMP.Left[int.Parse(SVMP.Original_SectionID.ElementAt(SVMP.CS_Count - 1).ToString())] == true)  //用来标记 主干道多车授权的最后一辆车是否离开其所需要的最后一个临界区 true 为离开，false为未离开
                    {
                        IsPass = true;
                    }


                    bool FlagOther = false;
                    while (Authorize_CS_to_Vehicle.Count != 0 && Authorize_CS_to_Vehicle.Count <= 3 && !IsPass)   //&&  Main.getGlobalTime() < StartTime
                    {

                        //次干道上的车辆单次授权
                        for (int b = 1; b <= this.MaxAuthNum / 4; b++)
                        {

                            if (Authorize_CS_to_Vehicle.Count == 3)
                            {
                                SuperVehicleManager svmpauththree = null;
                                svmpauththree = GetOneEmptyCSCar();
                                if (svmpauththree == null)
                                {
                                    FlagOther = true;
                                    break;
                                }
                                if (svmpauththree != null && svmpauththree.Te[svmpauththree.CS_Count] > SVMP.Te[SVMP.CS_Count])//-0.5
                                {
                                    FlagOther = true;
                                    break;
                                }
                                CSID = int.Parse(svmpauththree.SectionID.ElementAt(0).ToString());
                                ID = svmpauththree.getID();

                                                                

                                if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                {
                                    Authorize_CS_to_Vehicle.Add(CSID, null);
                                    Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                    Authorize_CS_to_Vehicle[CSID].Add(ID);
                                }
                                else
                                {
                                    if (!Authorize_CS_to_Vehicle[CSID].Contains(ID))
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }

                                    //这里的0需要修改 2018 6 5 需要单步调试
                                    Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                    string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                    int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                    Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[CSID].ElementAt(0));
                                    string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                    int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());


                                    if (LaneIDtemp1 != LaneIDtemp2)
                                    {
                                        this.Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                    }

                                    ////如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                    //if (LaneIDtemp != Authorize_CS_to_Vehicle[CSID].ElementAt(0).ElementAt(0))
                                    //{
                                    //    this.Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                    //}

                                }
                                if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                {
                                    this.sendMessage(Definitions.MsgAuthorize, ID, svmpauththree.Original_Priority, CSID,Intersection);
                                    IsAuth[CSID] = true;
                                    this.setToken(CSID, ID);
                                }
                                else
                                {
                                    Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                    if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                    {
                                        Authorize_CS_to_Vehicle.Remove(CSID);
                                    }
                                }
                                this.AddCarInAuthList(svmpauththree);
                            }
                            else if (Authorize_CS_to_Vehicle.Count == 2)
                            {
                                SuperVehicleManager svmpauthtwo = null;
                                svmpauthtwo = GetTwoEmptyCSCar();
                                if (svmpauthtwo == null)
                                {
                                    FlagOther = true;
                                    break;
                                }
                                if (svmpauthtwo != null && svmpauthtwo.Te[svmpauthtwo.CS_Count] > SVMP.Te[SVMP.CS_Count]) //-0.5
                                {
                                    FlagOther = true;
                                    break;
                                }
                                if (svmpauthtwo.CS_Count == 1)
                                {
                                    CSID = int.Parse(svmpauthtwo.SectionID.ElementAt(0).ToString());
                                    ID = svmpauthtwo.getID();

                                    
                                    if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                    {
                                        Authorize_CS_to_Vehicle.Add(CSID, null);
                                        Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    else
                                    {
                                        if (!Authorize_CS_to_Vehicle[CSID].Contains(ID))
                                        {
                                            Authorize_CS_to_Vehicle[CSID].Add(ID);
                                        }

                                        //这里的0需要修改 2018 6 5 需要单步调试
                                        Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                        string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                        int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                        Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[CSID].ElementAt(0));
                                        string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                        int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());


                                        if (LaneIDtemp1 != LaneIDtemp2)
                                        {
                                            this.Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        }

                                        //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                        //if (LaneIDtemp != Authorize_CS_to_Vehicle[CSID].ElementAt(0).ElementAt(0))
                                        //{
                                        //    this.Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        //}

                                    }
                                    if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                    {
                                        this.sendMessage(Definitions.MsgAuthorize, ID, svmpauthtwo.Original_Priority, CSID, Intersection);
                                        IsAuth[CSID] = true;
                                        this.setToken(CSID, ID);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                        {
                                            Authorize_CS_to_Vehicle.Remove(CSID);
                                        }
                                    }
                                    this.AddCarInAuthList(svmpauthtwo);
                                }
                                else
                                {

                                    for (int q = 1; q <= 2; q++)
                                    {
                                        CSID = int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString());
                                        ID = svmpauthtwo.getID();
                                        if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                        {
                                            Authorize_CS_to_Vehicle.Add(CSID, null);
                                            Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                            Authorize_CS_to_Vehicle[CSID].Add(ID);
                                        }
                                        else
                                        {
                                            if (!Authorize_CS_to_Vehicle[CSID].Contains(ID))
                                            {
                                                Authorize_CS_to_Vehicle[CSID].Add(ID);
                                            }


                                            //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                            //xc
                                            Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                            string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                            int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                            int temp = int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString());
                                            Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[temp].ElementAt(0));
                                            string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                            int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());
                                            

                                            //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                            //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString())].ElementAt(0).ElementAt(0))
                                            if (LaneIDtemp1 != LaneIDtemp2)
                                            {
                                                this.Authorize_CS_to_Vehicle[int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString())].Remove(ID);
                                                if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                                {
                                                    Authorize_CS_to_Vehicle.Remove(CSID);
                                                }
                                                for (int w = 1; w <= 4; w++)
                                                {
                                                    foreach (string str in Authorize_CS_to_Vehicle[w])
                                                    {
                                                        if (str == ID)
                                                        {
                                                            Authorize_CS_to_Vehicle[w].Remove(ID);
                                                            if (Authorize_CS_to_Vehicle[w].Count == 0)
                                                            {
                                                                Authorize_CS_to_Vehicle.Remove(w);
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                        if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                        {
                                            this.sendMessage(Definitions.MsgAuthorize, ID, svmpauthtwo.Original_Priority, CSID,Intersection);
                                            IsAuth[CSID] = true;
                                            this.setToken(CSID, ID);
                                        }
                                        else
                                        {
                                            Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                            if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                            {
                                                Authorize_CS_to_Vehicle.Remove(CSID);
                                            }


                                            for (int w = 1; w <= 4; w++)
                                            {
                                                foreach (string str in Authorize_CS_to_Vehicle[w])
                                                {
                                                    if (str == ID)
                                                    {
                                                        Authorize_CS_to_Vehicle[w].Remove(ID);
                                                        if (Authorize_CS_to_Vehicle[w].Count == 0)
                                                        {
                                                            Authorize_CS_to_Vehicle.Remove(w);
                                                        }
                                                    }
                                                }
                                            }



                                        }
                                    }
                                    this.AddCarInAuthList(svmpauthtwo);
                                }

                            }
                            else if (Authorize_CS_to_Vehicle.Count == 1)
                            {
                                SuperVehicleManager svmpauthone = null;
                                svmpauthone = GetThreeEmptyCSCar();
                                if (svmpauthone == null)
                                {
                                    FlagOther = true;
                                    break;
                                }
                                if (svmpauthone != null && svmpauthone.Te[svmpauthone.CS_Count] > SVMP.Te[SVMP.CS_Count])  //-0.5
                                {
                                    FlagOther = true;
                                    break;
                                }
                                if (svmpauthone.CS_Count == 1)
                                {
                                    CSID = int.Parse(svmpauthone.SectionID.ElementAt(0).ToString());
                                    ID = svmpauthone.getID();
                                    if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                    {
                                        Authorize_CS_to_Vehicle.Add(CSID, null);
                                        Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    else
                                    {
                                        if (!Authorize_CS_to_Vehicle[CSID].Contains(ID))
                                        {
                                            Authorize_CS_to_Vehicle[CSID].Add(ID);
                                        }


                                        //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                        //xc
                                        Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                        string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                        int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());
                                        
                                        Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[CSID].ElementAt(0));
                                        string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                        int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());

                                        if (LaneIDtemp1 != LaneIDtemp2)
                                        {
                                            this.Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        }
                                    }
                                    if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                    {
                                        this.sendMessage(Definitions.MsgAuthorize, ID, svmpauthone.Original_Priority, CSID,Intersection);
                                        IsAuth[CSID] = true;
                                        this.setToken(CSID, ID);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                        {
                                            Authorize_CS_to_Vehicle.Remove(CSID);

                                            if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                            {
                                                Authorize_CS_to_Vehicle.Remove(CSID);
                                            }


                                            for (int w = 1; w <= 4; w++)
                                            {
                                                foreach (string str in Authorize_CS_to_Vehicle[w])
                                                {
                                                    if (str == ID)
                                                    {
                                                        Authorize_CS_to_Vehicle[w].Remove(ID);
                                                        if (Authorize_CS_to_Vehicle[w].Count == 0)
                                                        {
                                                            Authorize_CS_to_Vehicle.Remove(w);
                                                        }
                                                    }
                                                }
                                            }


                                        }
                                    }
                                    this.AddCarInAuthList(svmpauthone);
                                }
                                else
                                {

                                    for (int q = 1; q <= svmpauthone.CS_Count; q++)
                                    {
                                        CSID = int.Parse(svmpauthone.SectionID.ElementAt(q - 1).ToString());
                                        ID = svmpauthone.getID();
                                        if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                        {
                                            Authorize_CS_to_Vehicle.Add(CSID, null);
                                            Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                            Authorize_CS_to_Vehicle[CSID].Add(ID);
                                        }
                                        else
                                        {
                                            if (!Authorize_CS_to_Vehicle[CSID].Contains(ID))
                                            {
                                                Authorize_CS_to_Vehicle[CSID].Add(ID);
                                            }


                                            //xc
                                            Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                            string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                            int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                            int temp = int.Parse(svmpauthone.SectionID.ElementAt(q - 1).ToString());
                                            Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[temp].ElementAt(0));
                                            string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                            int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());


                                            if (LaneIDtemp1 != LaneIDtemp2)
                                            //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                            //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[int.Parse(svmpauthone.SectionID.ElementAt(q - 1).ToString())].ElementAt(0).ElementAt(0))
                                            {
                                                this.Authorize_CS_to_Vehicle[int.Parse(svmpauthone.SectionID.ElementAt(q - 1).ToString())].Remove(ID);

                                                if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                                {
                                                    Authorize_CS_to_Vehicle.Remove(CSID);
                                                }


                                                for (int w = 1; w <= 4; w++)
                                                {
                                                    foreach (string str in Authorize_CS_to_Vehicle[w])
                                                    {
                                                        if (str == ID)
                                                        {
                                                            Authorize_CS_to_Vehicle[w].Remove(ID);
                                                            if (Authorize_CS_to_Vehicle[w].Count == 0)
                                                            {
                                                                Authorize_CS_to_Vehicle.Remove(w);
                                                            }
                                                        }
                                                    }
                                                }



                                            }
                                        }
                                        if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                        {
                                            this.sendMessage(Definitions.MsgAuthorize, ID, svmpauthone.Original_Priority, CSID,Intersection);
                                            IsAuth[CSID] = true;
                                            this.setToken(CSID, ID);
                                        }
                                        else
                                        {
                                            Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                            if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                            {
                                                Authorize_CS_to_Vehicle.Remove(CSID);

                                                if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                                {
                                                    Authorize_CS_to_Vehicle.Remove(CSID);
                                                }


                                                for (int w = 1; w <= 4; w++)
                                                {
                                                    foreach (string str in Authorize_CS_to_Vehicle[w])
                                                    {
                                                        if (str == ID)
                                                        {
                                                            Authorize_CS_to_Vehicle[w].Remove(ID);
                                                            if (Authorize_CS_to_Vehicle[w].Count == 0)
                                                            {
                                                                Authorize_CS_to_Vehicle.Remove(w);
                                                            }
                                                        }
                                                    }
                                                }



                                            }
                                        }
                                    }
                                    this.AddCarInAuthList(svmpauthone);
                                }

                            }


                        }

                        if (FlagOther == true)
                        {
                            break;
                        }

                    }

                }
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.GetType());
            }

        }


        /************************************************************************/
        /* 找到车辆到达所需第一个临界区(即为车道号)时间最短的车辆
         *                                                                       */
        /************************************************************************/
        private SuperVehicleManager GetArriveFirstSCSCar(Intersection Intersection)
        {
            SuperVehicleManager[] svm = new SuperVehicleManager[5];

            float[] time = new float[5]; //其中每一个元素 对应其LaneQueue中 第一辆车到达 其所需第一个临界区的时间
            string[] IDString = new string[5];
            int[] IDInt = new int[5];
            int[] xiabiao = new int[5];

            for (int m = 1; m <= 4; m++)  //初始化 使其时间都为0
            {
                //xiabiao[m] = 9999;
                xiabiao[1] = 9999;
                xiabiao[2] = 9998;
                xiabiao[3] = 9997;
                xiabiao[4] = 9996;
            }

            //若LaneQueue中有车辆，则将四个LaneQueue的首车添加到数组svm中
            int i = 1, j = 1;
            for (i = 1; i <= 4; i++)
            {
                if (LaneQueue[i].Count == 0)
                {
                    j++;
                    continue;
                }
                else
                {
                    svm[j] = LaneQueue[i].ElementAt(0);
                    IDString[j] = LaneQueue[i].ElementAt(0).getID();
                    j++;
                }
            }

            //获取进入预约线的所有车辆
            List<string> ListTemp = Intersection.GetReservationLst();
            if (ListTemp.Count != 0)
            {
                for (int j1 = 1; j1 <= 4; j1++)
                {
                    for (int j2 = 0; j2 < ListTemp.Count; j2++)
                    {
                        if (svm[j1] == null)
                        {
                            continue;
                        }
                        if (svm[j1].getID() == ListTemp[j2])
                        {
                            xiabiao[j1] = j2;
                        }
                    }
                }

            }

            int Flag = 1;
            for (int m = 1; m < 4; m++)
            {
                if (xiabiao[m + 1] - xiabiao[Flag] < 0)    //if (time[m + 1] < time[m])
                {
                    Flag = m + 1;
                }
            }



            //在一个时间片内，如果选中的车辆的 第一个临界区 isSelect 被标记为 true ，则说明该车辆之前已经被选中过，此时说明没有找到 车辆
            if (svm[Flag] != null)
            {
                for (int k1 = 0; k1 < CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].Count; k1++)
                {
                    VehicleManager vmp = null;
                    vmp = CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].ElementAt(k1).Value;
                    if (svm[Flag].getID() == vmp.getID())
                    {
                        if (CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].ElementAt(k1).Value.isSelect == true)
                        {
                            return null;
                        }
                    }
                }
            }

            //在一个时间片内，选中的车辆的 第一个临界区 isSelect 被标记为 true
            if (Already_Authorized_All_CS_Vehicles.Contains(svm[Flag].getID()))
            {
                return null;

                //MessageBox.Show("error,该车辆的所有临界区已经被授权！");
            }

            if (svm[Flag] != null)
            {
                for (int k1 = 0; k1 < CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].Count; k1++)
                {
                    VehicleManager vmp = null;
                    vmp = CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].ElementAt(k1).Value;
                    if (svm[Flag].getID() == vmp.getID())
                    {
                        CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].ElementAt(k1).Value.isSelect = true;
                        break;
                    }
                }
            }


            return svm[Flag];
        }




        /************************************************************************/
        /* 已知一辆车的ID，判断这辆车是否在车道上  
         *  通过该车行驶的距离 与 90?? 作比较                                   */
        /************************************************************************/
        private bool IsInLane(string ID1)
        {

            for (int i = 1; i <= 4; i++)
            {
                foreach (SuperVehicleManager svmp in LaneQueue[i])
                {
                    if (ID1 == svmp.getID())
                    {
                        if (svmp.getTotal_Dis() <= 90)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }

            return true;
        }

        /************************************************************************/
        /* 已知一辆车的ID1，
         * 且这辆车在车道上(找的前提)，则找到这辆车所在车道上的 后续车辆的ID0   
         *                ID01 = LaneQueue[i].ElementAt(j+1).getID();           */
        /************************************************************************/
        private Vehicle CarInLaneNext(string ID00)
        {
            string ID01 = null;
            int j = -1;

            for (int i = 1; i <= 4; i++)
            {
                foreach (SuperVehicleManager svmp in LaneQueue[i])
                {
                    if (ID00 == svmp.getID())
                    {
                        j = LaneQueue[i].IndexOf(svmp);
                        if (LaneQueue[i].Count > j + 1)
                        {
                            ID01 = LaneQueue[i].ElementAt(j + 1).getID();
                        }
                        else
                        {
                            //返回ID信息不够，返回车辆Vehicle对象  xc
                            for (int k = 0; k < MainData.Map.GlobalVehicleList.Count(); k++)
                            {
                                Vehicle veh = MainData.Map.GlobalVehicleList[k];
                                if (veh.Get_ID() == ID00)
                                {
                                    return veh;
                                }
                            }
                            // return ID00;
                        }
                    }
                }

                // ID0 = LaneQueue[i].ElementAt(j+1).getID();
            }

            //返回ID信息不够，返回车辆Vehicle对象   xc
            for (int i = 0; i < MainData.Map.GlobalVehicleList.Count(); i++)
            {
                Vehicle veh = MainData.Map.GlobalVehicleList[i];
                if (veh.Get_ID() == ID01)
                {
                    return veh;
                }
            }

            return null;
            //return ID01;
        }
       

        /************************************************************************/
        /* 获取各个道路列表中最早到达的车辆,用于每次先进行判断的车辆，返回车辆的ID号                                                                     */
        /************************************************************************/
        private VehicleManager GetEarliestFromCSVehicle()
        {
            VehicleManager vtmp = null;
            VehicleManager SelTmp = null;
            float EarliestTime = 99999.0f;
            int ChosenCS = 0;       //标志所选中的CS号
            int ChosenVehi = 0;     //标志所选中车道中的车辆的ID号

            for (int i = 1; i < 5; ++i)
            {
                if (this.Token[i] == 0)   //为0则表示该资源空闲
                {
                    for (int j = 0; j < this.CS[i].Count; ++j)
                    {
                        vtmp = this.CS[i].ElementAt(j).Value;
                        string str = vtmp.getID();
                        //车辆已经经过该临界区
                        if ((vtmp.getTs() - Main.getGlobalTime()) <= 0.00000000001f)
                        {
                            Debug.Write("fdasdfdas");
                            continue;
                        }
                        if (Already_Authorized_All_CS_Vehicles.Contains(str))
                        {
                            //车辆的所有临界区已被授权
                            Debug.Write("fdasdfdas");
                            continue;
                        }
                        else
                        {
                            //车辆未被选中,则进行车辆的选择
                            if (vtmp.isSelect == false)
                            {
                                if ((EarliestTime - vtmp.getTs()) > 0.00000000001f)
                                {
                                    ChosenCS = i;
                                    ChosenVehi = j;
                                    EarliestTime = vtmp.getTs();
                                    SelTmp = vtmp;
                                }
                            }
                        }
                    }
                }
                else
                {

                }
            }
            if (SelTmp != null)
            {
                this.CS[ChosenCS].ElementAt(ChosenVehi).Value.isSelect = true;
            }
            return SelTmp;
        }

        /************************************************************************/
        /* 检验在道路消息队列组中的某一辆车是否，判断一辆是否是按照临界区先后循序进行申请的，返回true则非法                                                                     */
        /************************************************************************/
        private bool isTokenSequenceIllegal(int LaneID, string ID, int AuthCSID, ref string RepID)
        {
            SuperVehicleManager svm = null;
            int d = 0;

            //获取道路消息队列组中需要进行判断的车辆的总消息
            for (int i = 0; i < this.LaneQueue[LaneID].Count; i++)
            {
                if (this.LaneQueue[LaneID].ElementAt(i).ID == ID)
                {
                    svm = this.LaneQueue[LaneID].ElementAt(i);
                    break;
                }
            }

            if (svm != null)
            {
                //获取当前需要判断的临界区，即将要处理的临界区
                for (int i = 0; i < svm.CS_Count; i++)
                {
                    if (svm.VehicleManagers[int.Parse(svm.SectionID[i].ToString())] == null)
                    {
                        System.Windows.Forms.MessageBox.Show("error,isTokenSequenceIllegal1");
                        continue;
                    }
                    if (int.Parse(svm.SectionID[i].ToString()) == AuthCSID)
                    {
                        d = i;                          //若只需要一个临界区，则d=0；
                        break;
                    }
                }

                for (int i = 0; i < d; i++)
                {
                    //消息按照临界区序号进行存储
                    if (svm.VehicleManagers[int.Parse(svm.SectionID[i].ToString())] == null)
                    {
                        System.Windows.Forms.MessageBox.Show("error,isTokenSequenceIllegal2");
                        continue;
                    }
                    //车辆的所申请临界区之前的临界区已经申请完成，且所申请临界区该临界区还未申请成功，此时则说明合法
                    if (svm.VehicleManagers[int.Parse(svm.SectionID[i].ToString())].HasToken == false)
                    {
                        //                        Debug.WriteLine("Illegal \t" + ID + "\t" + AuthCSID + "\t" + svm.SectionID);
                        RepID = ID;
                        return true;
                    }
                }
            }
            else
            {
                //test
                //Debug.WriteLine("fjkafds");
                //test finish
            }
            return false;
        }

        /************************************************************************/
        /* 检验当前授权车辆是否是道路中的第一辆车,若是首车，则返回true                                                                     */
        /************************************************************************/
        private bool isFirstVehicleInLane(int LaneID, string ID, int CSID)
        {
            SuperVehicleManager ktmp;
            string scs = null;
            int k = 0;
            int k2 = 1;
            //找到正在判断的车辆
            foreach (SuperVehicleManager kvp in LaneQueue[LaneID])
            {
                if (kvp.ID == ID)
                {
                    ktmp = kvp;
                    scs = ktmp.Original_SectionID;
                    break;
                }
                ++k;
            }
            //正在判断中车辆所申请临界区在其所用临界区中所处的位置
            for (int i = 0; i < scs.Length; ++i)
            {
                if (CSID != int.Parse(scs[i].ToString()))
                {
                    ++k2;
                }
                else
                {
                    break;
                }
            }
            //判断是否是首车
            bool mark = true;   //若是首车，则mark为true
            for (int i = 0; i < k; ++i)   //遍历申请车辆之前的所有车
            {
                for (int j = 0; j < k2; ++j)  //遍历包含所申请临界区之前的所有临界区
                {
                    string pre_scs = LaneQueue[LaneID].ElementAt(i).Original_SectionID;
                    if (pre_scs.Contains(scs[j].ToString()) == true)//前车包含本车所要申请的临界区，此时需判断前车是否已经离开该临界区
                    {
                        if (LaneQueue[LaneID].ElementAt(i).Left[CSID] == true)  //前车已离开该临界区，本车已可申请该临界区
                        {

                        }
                        else
                        {
                            mark = false;
                        }
                    }
                    else    //前车未包含本车所要申请的临界区，此时无需判断前车是否已经离开该临界区
                    {

                    }
                }
            }

            if (mark == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /************************************************************************/
        /* 检测资源是否出现环路，若返回true，则产生了回路 
         * 1、若该临界区被走过，则说明产生了回路
         * 2、若未被走过，则判断其所需的下一临界区
         */
        /************************************************************************/
        private bool dfsCheckCircuit(int current)
        {
            if (Walked[current])
            {
                return true;
            }
            Walked[current] = true;
            for (int i = 1; i <= 4; i++)
            {
                if (this.SourceGraph[current, i])
                {
                    //若箭头存在，即该临界区需求下一临界区
                    //则继续判断该临界区是否会出现回路
                    if (dfsCheckCircuit(i))
                    {
                        return true;
                    }
                }
            }
            Walked[current] = false;
            return false;
        }


        /************************************************************************/
        /* 判断是否会出现死锁，返回True则死锁产生    
         * 此时SQ.Count 表示临界区被授权的个数，而count表示各个临界区被授权车辆个数的总和
             key     Value
         *    0       234
         *            242
         *    1       356
         *            423       
         */
        /************************************************************************/
        private bool isTokenSequenceDeadLock(Dictionary<int, List<string>> SQ)
        {
            int i, j;
            int Count = 0;
            int[] array = new int[5];

            for (i = 0; i < 5; i++)
            {
                for (j = 0; j < 5; j++)
                {
                    this.SourceGraph[i, j] = false;
                }
                this.Walked[i] = false;
            }

            //先计算出SQ 中被授权车辆个数的总和 Count
            for (int Key = 0; Key < SQ.Count; Key++)
            {
                int ListIndex = 0;
                for (; ListIndex < SQ.Values.ElementAt(Key).Count; Count++, ListIndex++)
                {

                }
            }
            SuperVehicleManager[] svm = new SuperVehicleManager[Count];

            int xiabiao = 0;    //svm数组中的 下标

            //获取待授权的所有车辆的车辆superManager信息，存入svm中
            for (int Key = 0; Key < SQ.Count; Key++)   //对应到每一个临界区
            {
                int ListIndex = 0;
                for (; ListIndex < SQ.Values.ElementAt(Key).Count && xiabiao < Count; ListIndex++)        //每一个临界区 所对应的 授权车辆 队列
                {
                    string VehicleID = SQ.ElementAt(Key).Value[ListIndex]; //车辆ID
                    Vehicle VehicleTemp = FindVehicleByID(VehicleID);      //车辆对象
                    string LaneIDTemp = VehicleTemp.Get_Current_LaneID();  //车辆所在LaneID

                    for (int k = 1; k <= 4; k++) 
                    {
                        for (j = 0; j < this.LaneQueue[k].Count; j++)
                        {

                            //Test将授权信息全部写入到文件中 2018.5.28
                            //DateTime DT = System.DateTime.Now;
                            //string text = System.IO.File.ReadAllText(@"D:\IOTest\HWFP-SQ-SV Test.txt");
                            //text += DT.ToString() + " ID1 " + this.LaneQueue[int.Parse(LaneIDTemp.ElementAt(5).ToString())].ElementAt(j).ID;
                            //text += "    ID2 " + SQ.ElementAt(Key).Value[ListIndex] + "\r\n";
                            //System.IO.File.WriteAllText(@"D:\IOTest\HWFP-SQ-SV Test.txt", text);
                            //Test


                            if (this.LaneQueue[k].ElementAt(j).ID == SQ.ElementAt(Key).Value[ListIndex])   //每一辆车 需要对应到一个lanequeue队列 找到它
                            {
                                svm[xiabiao] = this.LaneQueue[k].ElementAt(j);
                                xiabiao++;
                                break;
                            }

                        }
                    }

                       


                }
            }


            //构建资源分配表
            for (i = 0; (i + 3) < 7; ++i)
            {//临界区标号
                for (j = 0; j < Count; j++)
                {//车辆数目

                    if (svm[j] == null)
                    {
                        int test = MainData.Map.GlobalVehicleList.Count;
                    }

                    if (int.Parse(svm[j].SectionID[i].ToString()) != 0)
                    {
                        if (svm[j].Left[int.Parse(svm[j].SectionID[i].ToString())] == false)
                        {//若该临界区未走过，则将其下面要走的路径标志为true
                            if (int.Parse(svm[j].SectionID[i + 1].ToString()) != 0)
                            {
                                this.SourceGraph[int.Parse(svm[j].SectionID[i].ToString()), int.Parse(svm[j].SectionID[i + 1].ToString())] = true;
                            }
                            if (int.Parse(svm[j].SectionID[i + 2].ToString()) != 0)
                            {
                                this.SourceGraph[int.Parse(svm[j].SectionID[i + 1].ToString()), int.Parse(svm[j].SectionID[i + 2].ToString())] = true;
                            }
                            if (int.Parse(svm[j].SectionID[i + 3].ToString()) != 0)
                            {
                                this.SourceGraph[int.Parse(svm[j].SectionID[i + 2].ToString()), int.Parse(svm[j].SectionID[i + 3].ToString())] = true;
                            }
                        }
                        else
                        {//如果车辆已离开该临界区则无需在将临界区加入继续判断是否会死锁
                            /*                            Debug.WriteLine("fdasfsd");*/
                        }
                    }
                    else
                    {//若车辆为经过该临界区

                    }
                }
            }

            //检查是否有回路出现
            for (i = 1; i <= 4; i++)
            {
                //从第一个临界区开始检测，通过递归的方式，检测其所需要的临界区是否被走过，
                //若走过，那么就会出现环路
                if (dfsCheckCircuit(i))
                {
                    return true;
                }
            }
            return false;
        }

        /************************************************************************/
        /* 判断是否会出现死锁，返回True则死锁产生    
         * 此时SQ.Count 表示临界区被授权的个数，而count表示各个临界区被授权车辆个数的总和
             key     Value
         *    0       234
         *            242
         *    1       356
         *            423       
         */
        /************************************************************************/
        private bool isTokenSequenceDeadLock1(Dictionary<int, List<string>> SQ)
        {
            int i, j;
            int Count = 0;
            int[] array = new int[5];

            for (i = 0; i < 5; i++)
            {
                for (j = 0; j < 5; j++)
                {
                    this.SourceGraph[i, j] = false;
                }
                this.Walked[i] = false;
            }

            //先计算出SQ 中被授权车辆个数的总和 Count
            for (int Key = 0; Key < SQ.Count; Key++)
            {
                int ListIndex = 0;
                for (; ListIndex < SQ.Values.ElementAt(Key).Count; Count++, ListIndex++)
                {

                }
            }
            SuperVehicleManager[] svm = new SuperVehicleManager[Count];

            int xiabiao = 0;    //svm数组中的 下标

            //获取待授权的所有车辆的车辆superManager信息，存入svm中
            for (int Key = 0; Key < SQ.Count; Key++)   //对应到每一个临界区
            {
                int ListIndex = 0;
                for (; ListIndex < SQ.Values.ElementAt(Key).Count && xiabiao < Count; ListIndex++)        //每一个临界区 所对应的 授权车辆 队列
                {
                    string VehicleID = SQ.ElementAt(Key).Value[ListIndex]; //车辆ID
                    Vehicle VehicleTemp = FindVehicleByID(VehicleID);      //车辆对象
                    string LaneIDTemp = VehicleTemp.Get_Current_LaneID();  //车辆所在LaneID

                    for (j = 0; j < this.LaneQueue[int.Parse(LaneIDTemp.ElementAt(5).ToString())].Count; j++)
                    {

                        //Test将授权信息全部写入到文件中 2018.5.28
                        DateTime DT = System.DateTime.Now;
                        string text = System.IO.File.ReadAllText(@"D:\IOTest\HWFP-SQ-SV Test.txt");
                        text += DT.ToString() + " ID1 " + this.LaneQueue[int.Parse(LaneIDTemp.ElementAt(5).ToString())].ElementAt(j).ID;
                        text += "    ID2 " +SQ.ElementAt(Key).Value[ListIndex] +"\r\n";
                        System.IO.File.WriteAllText(@"D:\IOTest\HWFP-SQ-SV Test.txt", text);                        
                        //Test


                        if (this.LaneQueue[int.Parse(LaneIDTemp.ElementAt(5).ToString())].ElementAt(j).ID == SQ.ElementAt(Key).Value[ListIndex])   //每一辆车 需要对应到一个lanequeue队列 找到它
                        {
                            svm[xiabiao] = this.LaneQueue[int.Parse(LaneIDTemp.ElementAt(5).ToString())].ElementAt(j);
                            xiabiao++;
                            break;
                        }
                        //else 
                        //{
                        //    //string LaneIDTempPrevious = VehicleTemp.Get_Previous_LaneID();  //车辆所在LaneID
                            //for (j = 0; j < this.LaneQueue[int.Parse(LaneIDTempPrevious.ElementAt(5).ToString())].Count; j++)
                            //{
                            //    if (this.LaneQueue[int.Parse(LaneIDTempPrevious.ElementAt(5).ToString())].ElementAt(j).ID == SQ.ElementAt(Key).Value[ListIndex])   //每一辆车 需要对应到一个lanequeue队列 找到它
                            //    {
                            //        svm[xiabiao] = this.LaneQueue[int.Parse(LaneIDTempPrevious.ElementAt(5).ToString())].ElementAt(j);
                            //        xiabiao++;
                            //        break;
                            //    }
                            //}
                        //}
                    }                   


                }
            }


            //构建资源分配表
            for (i = 0; (i + 3) < 7; ++i)
            {//临界区标号
                for (j = 0; j < Count; j++)
                {//车辆数目

                    if (svm[j] == null) 
                    {
                       int test = MainData.Map.GlobalVehicleList.Count;
                    }

                    if (int.Parse(svm[j].SectionID[i].ToString()) != 0)
                    {
                        if (svm[j].Left[int.Parse(svm[j].SectionID[i].ToString())] == false)
                        {//若该临界区未走过，则将其下面要走的路径标志为true
                            if (int.Parse(svm[j].SectionID[i + 1].ToString()) != 0)
                            {
                                this.SourceGraph[int.Parse(svm[j].SectionID[i].ToString()), int.Parse(svm[j].SectionID[i + 1].ToString())] = true;
                            }
                            if (int.Parse(svm[j].SectionID[i + 2].ToString()) != 0)
                            {
                                this.SourceGraph[int.Parse(svm[j].SectionID[i + 1].ToString()), int.Parse(svm[j].SectionID[i + 2].ToString())] = true;
                            }
                            if (int.Parse(svm[j].SectionID[i + 3].ToString()) != 0)
                            {
                                this.SourceGraph[int.Parse(svm[j].SectionID[i + 2].ToString()), int.Parse(svm[j].SectionID[i + 3].ToString())] = true;
                            }
                        }
                        else
                        {//如果车辆已离开该临界区则无需在将临界区加入继续判断是否会死锁
                            /*                            Debug.WriteLine("fdasfsd");*/
                        }
                    }
                    else
                    {//若车辆为经过该临界区

                    }
                }
            }

            //检查是否有回路出现
            for (i = 1; i <= 4; i++)
            {
                //从第一个临界区开始检测，通过递归的方式，检测其所需要的临界区是否被走过，
                //若走过，那么就会出现环路
                if (dfsCheckCircuit(i))
                {
                    return true;
                }
            }
            return false;
        }


        /************************************************************************/
        /* 当临界区授权情况改变时，包括新授权和授权收回的情况，输出此时占用临界区的车辆，全局时间等信息。                                                                     */
        /************************************************************************/
        private void OutPutAuthMsg(int mark, Message msg)
        {
        }

        /************************************************************************/
        /* 发送临界区授权信息                                                                     */
        /************************************************************************/
        private void sendMessage(int Type, String ID, int Priority, int CSID, Intersection Intersection)
        {
            this.MsgCount++;
            float[] ts = new float[5];
            float[] te = new float[5];
            switch (Type)
            {
                case Definitions.MsgAuthorize:
                    Message m = new Message(Definitions.MsgAuthorize, Definitions.Agent, ID,
                            ts, te, -1.0f, Priority, CSID.ToString(), -1,"");

                    //写到消息队列
                    List<Message> AtoV_BufferTemp = Intersection.GetAtoV_Buffer();
                    AtoV_BufferTemp.Add(m);
                    Intersection.SetAtoV_Buffer(AtoV_BufferTemp);
                    MainData.UpdateIntersectionList(Intersection);

                    //Msg_Buffer.AtoV_Buffer.Enqueue(m);
                    this.Token[CSID]++;
                    this.OutPutAuthMsg(1, m);
                    break;
                case Definitions.MsgRefuse:
                    break;
                default:
                    System.Windows.Forms.MessageBox.Show("FWFP-SQ-SV 1637");
                    return;
            }
            float time = Main.getGlobalTime() + Main.TimeStep;

        }

        /************************************************************************/
        /* 设置授权信息，TokenID为被授权的临界区号，ID是被授权车辆                                                                     */
        /************************************************************************/
        private void setToken(int TokenID, string ID)
        {
            //  xc
            Vehicle Vehicle = FindVehicleByID(ID);
            string LaneID = Vehicle.Get_Current_LaneID();

            int j = 0;
            for (j = 0; j < this.LaneQueue[int.Parse(LaneID[5].ToString())].Count; j++)
            {
                if (this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).ID == ID)
                {
                    //LaneQueue中存储的信息

                    this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).HaveTokenCount++;
                    this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).Token[TokenID] = true;
                    this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).VehicleManagers[TokenID].HasToken = true;
                    for (int i = 0; i < 5; i++)
                    {
                        if (this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).VehicleManagers[i] != null)
                        {
                            this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).VehicleManagers[i].Token[TokenID] = true;
                        }
                    }
                }
            }

            //CS中存储的信息
            foreach (KeyValuePair<string, VehicleManager> kvp in this.CS[TokenID])
            {
                if (kvp.Key == ID)
                {
                    kvp.Value.HasToken = true;
                    kvp.Value.Token[TokenID] = true;
                }
            }
            for (int i = 0; i < 5; ++i)
            {
                foreach (KeyValuePair<string, VehicleManager> kvp in this.CS[i])
                {
                    if (kvp.Key == ID)
                    {
                        kvp.Value.Token[TokenID] = true;
                    }
                }
            }

            //本文件中的车道标志信息
            // this.Token[TokenID] ++;
            return;
        }

        /************************************************************************/
        /* 判断各临界区的申请队列是否为空                                                                     */
        /************************************************************************/
        private bool IsCSEmpty()
        {
            bool mark = true;
            for (int i = 1; i < 5; ++i)
            {
                if (this.CS[i].Count != 0)
                {
                    mark = false;
                }
            }
            return mark;
        }


        /************************************************************************/
        /* 检测是否有高优先级车辆出现在预约队列中,若有高优先级车辆出现，则返回true,否则返回false                                                                     */
        /************************************************************************/
        private bool isPriorVehiOccur()
        {
            bool mark = false;
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < this.LaneQueue[i].Count(); j++)
                {
                    if (this.LaneQueue[i].ElementAt(j).Priority == Definitions.Prio_High)
                    {
                        mark = true;
                        this.PriorType = Definitions.Prio_High;
                        return true;
                    }
                    else if (this.LaneQueue[i].ElementAt(j).Priority == Definitions.Prio_Mid)
                    {
                        mark = true;
                        this.PriorType = Definitions.Prio_Mid;
                    }
                }
            }
            if (mark == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /************************************************************************/
        /* 验证是否会出现LaneQueue中的车辆的Priority大于this.PriorType                                                                     */
        /************************************************************************/
        private void testPrior()
        {
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < this.LaneQueue[i].Count; j++)
                {
                    string ID = this.LaneQueue[i].ElementAt(j).ID;
                    SuperVehicleManager stmp = this.LaneQueue[i].ElementAt(j); 

                    if (stmp.Priority > this.PriorType)
                    {
                        System.Windows.Forms.MessageBox.Show("PriorRaised error");
                    }
                }
            }
        }

        /************************************************************************/
        /* 找到当前ID对应的LaneQueue中的位置，最终返回两个位置posx,posy，其中posx表示在第车道号，其中posy表示在在车道队列中的位置                                                                     */
        /************************************************************************/
        private SuperVehicleManager FindPosInLaneQueue(string ID)
        {
            Vehicle VehicleTemp = FindVehicleByID(ID);
            string LaneIDPrevious = VehicleTemp.Get_Previous_LaneID(); //车辆之前所在的车道序号

            SuperVehicleManager stmp = null;
            int i = int.Parse(LaneIDPrevious[5].ToString()); //第几个车道

            for (int j = 0; j < this.LaneQueue[i].Count; j++)
            {
                if (this.LaneQueue[i].ElementAt(j).ID == ID)
                {
                    return this.LaneQueue[i].ElementAt(j);
                }
            }
            return stmp;
        }


        /************************************************************************/
        /* 用于执行FIFO调度算法                                                                     */
        /************************************************************************/
        private void executeAlgorithmFIFO(Intersection Intersection)
        {
            this.processLeftVehicles(Intersection);
            //this.ReSetIsSelect();
        }





        /************************************************************************/
        /* 计算VehicleMng中第index（从0开始计数）辆车的延迟时间,(单辆车的延迟时间)
         * Index与IndexPre之间的车辆可不计入延迟时间计算
         * 参数：  int Index  需计算的车辆在VehicelMng中的位置
         *         int CSID_Origin  原高优先级车辆的第一个临界区
         *         int Priority     高优先级
         *         ref float FirstVehcielTs  第一辆被计入车辆的到达时间
         */
        /************************************************************************/
        private float computeDelayTimeInLane(int Index, int CSID, int Priority)
        {
            return 0;
        }





        /************************************************************************/
        /* 计算VehicleMng中第index（从0开始计数）辆车的延迟时间,(单辆车的延迟时间)
         * 
         * 参数：  int Index  需计算的车辆  位于哪一个车道
         *         Num  高优先级车辆在LaneQueue中的下标  从0开始
         *         
         *         
         */
        /************************************************************************/
        private float computeDelayTime(int Index, int Num, int Priority)
        {

            //若Num为-1，则说明该车道没有当前最高优先级车辆，返回9999.9
            if (Num == -1)
            {
                return 99999.0F;
            }


            Stack<int> Vehicle_count = new Stack<int>();

            int index_pre = 0;
            SuperVehicleManager stmp_pre = null;
            float ts_pre = 0, te_pre = 0;
            string ID_pre = "";

            int index_cur = 0;
            SuperVehicleManager stmp_cur = null;
            float ts_cur = 0, te_cur = 0;
            string ID_cur = "";

            //遍历所有的车辆
            for (int i = Num; i >= 0; i--)
            {
                Vehicle_count.Push(i);
            }

            //最终延迟时间
            float result = 0;
            if (Vehicle_count.Count == 1)
            {
                return 0;
            }

            while (Vehicle_count.Count > 1)
            {
                index_pre = Vehicle_count.Pop();
                stmp_pre = this.LaneQueue[Index].ElementAt(index_pre);
                ID_pre = stmp_pre.ID;
                ts_pre = stmp_pre.Ts[1];
                te_pre = stmp_pre.Te[stmp_pre.CS_Count];

                index_cur = Vehicle_count.Peek();
                stmp_cur = this.LaneQueue[Index].ElementAt(index_cur);
                ID_cur = stmp_cur.ID;
                ts_cur = stmp_cur.Ts[1];
                te_cur = stmp_cur.Te[stmp_cur.CS_Count];

                result += (te_pre - ts_cur);
            }
            return (float)Math.Round(result, Definitions.Precise);
        }


        /************************************************************************/
        /* 查找当前临界区CSID在section中的位置，返回其位置（从1开始计数）                                                                     */
        /************************************************************************/
        private int GetPosInSections(string sections, string CSID)
        {
            for (int i = 0; i < sections.Count(); i++)
            {
                if (sections[i].ToString() == CSID)
                {
                    return i + 1;
                }
            }
            return -1;
        }




        /************************************************************************/
        /* 寻找多车授权的 车道 
         */
        /************************************************************************/

        private int GetMulCarLane()
        {

            if (this.HighPriorLaneIDOrigin.Count == 1)
            {
                return HighPriorLaneIDOrigin.ElementAt(0);
            }
            else
            {
                return ChooseMaxWeight();
            }
        }


        private int FindHighVehPosInLaneQueue(int lanid)
        {
            int HighVehPos;
            for (int i = LaneQueue[lanid].Count() - 1; i >= 0; i--)
            {
                if (LaneQueue[lanid].ElementAt(i).Original_Priority == Definitions.Prio_High)
                {
                    HighVehPos = i;
                    return HighVehPos;
                }
            }
            return -1;
        }




        /************************************************************************/
        /* 寻找权重最大的车道 ，并返回车道的序号 
         */
        /************************************************************************/
        private int ChooseMaxWeight()
        {
            int[] highCarNum = new int[5];
            int[] midCarNum = new int[5];
            int[] lowCarNum = new int[5];

            int[] highCarFrontNum = new int[5];

            float[] Time = new float[5];

            int[] ResTimeStepSum = new int[5];

            //得到DelayTime[i]
            for (int i = 1; i <= 4; i++)
            {
                DelayTime[i] = 99999;

                highCarNum[i] = 0;
                midCarNum[i] = 0;
                lowCarNum[i] = 0;

                highCarFrontNum[i] = 0;

                Time[i] = 99999;

                ResTimeStepSum[i] = 0;

            }




            for (int i = 1; i <= 4; i++)
            {
                
                if (LaneQueue[i].Count == 0)
                {
                    continue;
                }

                highCarNum[i] = HighCarNum(i);
                midCarNum[i] = MidCarNum(i);
                lowCarNum[i] = LowCarNum(i);

                highCarFrontNum[i] = HighCarFrontNum(i);

                Time[i] = HighCarWaitTime(i);

                ResTimeStepSum[i] = ResTimeSum(i);
            }



            if (this.Authorize_CS_to_Vehicle.Count() == 0)
            {
                for (int m = 1; m <= 4; m++)
                {
                    Debug.WriteLine("HWFP-SQ-SV" + "\t" + this.PriorType + "\t" + m + "\t" + highCarNum[m] + "\t" + midCarNum[m] + "\t" + lowCarNum[m] + "\t" + ResTimeStepSum[m] + "\t" + Time[m] + "\t");
                }

            }


            //得到Weight[i]
            for (int i = 1; i <= 4; i++)
            {
                float GaMa = MainData.SimulationConfig.GetTxtServiceRatio();
                float BeiTa = MainData.SimulationConfig.GetTxtJamRatio();
                float DeErTa = MainData.SimulationConfig.GetTxtTimeRatio();

                Weight[i] = GaMa * ResTimeStepSum[i] / 1 + BeiTa * 1 * (Definitions.xishu1 * highCarNum[i] + Definitions.xishu2 * midCarNum[i] + Definitions.xishu3 * lowCarNum[i]) + highCarFrontNum[i] + DeErTa * 1 / Time[i];
            }//ResTimeStepSum[i] 预约等待时间 = （全局时间-预约时刻）/0.04 ，不是延迟时间




            //若有高优先级车辆存在时，对没有高优先级车辆所在的车道的 Weigh置0
            if (this.PriorType == Definitions.Prio_High && HighPriorVehicleOrigin.Count() != 0)
            {
                for (int m = 1; m < 5; m++)
                {
                    bool IsHighCar = false;
                    for (int b = 0; b < LaneQueue[m].Count(); b++)
                    {
                        if (LaneQueue[m].ElementAt(b).Original_Priority == Definitions.Prio_High)
                        {
                            IsHighCar = true;
                        }
                    }

                    if (!IsHighCar || LaneQueue[m].Count() == 0)
                    {
                        Weight[m] = 0;
                    }

                }

            }



            //找到最大的Weight[i]，并返回相应的i
            float max = Weight[1];
            for (int i = 2; i <= 4; i++)
            {
                if (Weight[i] > max)
                {
                    max = Weight[i];
                }
            }
            for (int i = 1; i <= 4; i++)
            {
                if (Weight[i] == max)
                {
                    return i;
                }
            }

            return -1;
        }



        /************************************************************************/
        /* 获取当前的原高优先级车辆和原高优先级车辆车道                                                                     */
        /************************************************************************/
        private void OriginalHighPriorVehicleQueueCreate(int priority)
        {
            this.HighPriorVehicleOrigin.Clear();
            this.HighPriorLaneIDOrigin.Clear();
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < this.LaneQueue[i].Count; j++)
                {
                    //选择优先级为priority优先级的车辆
                    if (this.LaneQueue[i].ElementAt(j).Original_Priority == priority)
                    {
                        if (this.HighPriorVehicleOrigin.Contains(this.LaneQueue[i].ElementAt(j).ID) == false)
                        {
                            this.HighPriorVehicleOrigin.Add(this.LaneQueue[i].ElementAt(j).ID);
                        }


                        //添加到HighPriorLaneIDOrigin队列中
                        string sections = this.LaneQueue[i].ElementAt(j).Original_SectionID;
                        bool mark = true;
                        for (int k = 0; k < sections.Count(); k++)
                        {
                            int CSID = int.Parse(sections[k].ToString());
                            if (this.LaneQueue[i].ElementAt(j).Left[CSID] == true || this.LaneQueue[i].ElementAt(j).Token[CSID] == true)
                            {
                                mark = false;
                            }
                        }
                        if (mark && this.HighPriorLaneIDOrigin.Contains(i) == false)
                        {
                            this.HighPriorLaneIDOrigin.Add(i);
                        }
                    }
                }
            }
        }


        /************************************************************************/
        /* 用于执行Prio调度算法                                                                     */
        /************************************************************************/
        private void executeAlgorithmPrior(Intersection Intersection)
        {
            //被授权车辆超过4辆
            if (this.Authorized_Vehicle_Sequence.Count > 4 * this.MaxAuthNum)
            {
                System.Windows.Forms.MessageBox.Show("HWFP-SQ-SV 2164");
                return;
            }

            //按照出现高优先级或者中优先级的不同情况进行分类
            if (this.PriorType == Definitions.Prio_High)
            {
                this.processPriority(Definitions.Prio_High,Intersection);
            }
            else if (this.PriorType == Definitions.Prio_Mid)
            {
                this.processPriority(Definitions.Prio_Mid,Intersection);
            }
            

            this.ReSetIsSelect();
        }


        /************************************************************************/
        /* 将车辆是否选中、判断信息置位                                                                     */
        /************************************************************************/
        private void ReSetIsSelect()
        {
            for (int i = 0; i < 5; ++i)
            {
                for (int j = 0; j < this.CS[i].Count; ++j)
                {
                    this.CS[i].ElementAt(j).Value.isSelect = false;
                }
            }
            for (int i = 0; i < 5; ++i)
            {
                for (int j = 0; j < this.LaneQueue[i].Count; j++)
                {
                    this.LaneQueue[i].ElementAt(j).IsJudged = false;
                }
            }
            for (int i = 0; i < this.VehicleMng.Count; i++)
            {
                this.VehicleMng.ElementAt(i).Value.IsJudged = false;
            }


        }

        /************************************************************************/
        /* 找到四个车道中权重系数最大的车道的首车   
         *                                                                       */
        /************************************************************************/
        private SuperVehicleManager GetPriorFirstSCSCar()
        {
            SuperVehicleManager stmp = null;
            int lanid = ChooseMaxWeight();

            if (this.LaneQueue[lanid].Count != 0)
            {
                stmp = LaneQueue[lanid].ElementAt(0);
            }
            return stmp;
        }




        /************************************************************************/
        /* 多车授权较高优先级车辆                                                                     */
        /************************************************************************/
        private void processPriority(int Priority, Intersection Intersection)
        {

            string s = null;
            int CSID = 0;
            string ID = null;
            string ID0 = null;



            s = null;
            if (!IsCSEmpty())           //判断各临界区的申请队列是否为空 ,
            {
                
                //若存在临界区未被占用
                SuperVehicleManager svmp = null;

                SuperVehicleManager svmplater = null;
                while ((svmp = this.GetPriorFirstSCSCar()) != null)
                {
                    if (this.PriorType == Definitions.Prio_High)
                    {
                        //xc
                        Vehicle VehicleTemp = FindVehicleByID(svmp.getID());
                        string LaneIDPrevious = VehicleTemp.Get_Current_LaneID(); //车辆之前所在的车道序号
                        int LaneIDtemp = int.Parse(LaneIDPrevious[5].ToString());

                        AuthNum = FindHighVehPosInLaneQueue(LaneIDtemp) + 1;
                    }
                    //AuthNum = FindHighVehPosInLaneQueue(int.Parse(svmp.getID().ElementAt(0).ToString())) +1;
                    if (AuthNum < this.MaxAuthNum / 4)
                    {
                        AuthNum = this.MaxAuthNum / 4;
                    }

                    if (AuthNum > this.MaxAuthNum / 4)
                    {
                        if (this.PriorType != Definitions.Prio_High)
                        {
                            AuthNum = this.MaxAuthNum / 4;
                        }
                    }

                    //临界区未分配完毕，则继续
                    if (this.Token[1] == 0 && this.Token[2] == 0 && this.Token[3] == 0 && this.Token[4] == 0)
                    {
                        // continue;
                    }
                    else
                    {
                        break;
                    }

                    IsPass = false;
                    SVMP = svmp;
                    //被选中车辆的ID
                    ID = svmp.getID();

                    //找到车辆Vehicle对象的LaneID                        
                    string LaneID = FindVehicleByID(ID).Get_Current_LaneID();  

                    //被选中车辆的CSID 
                    CSID = int.Parse(svmp.SectionID.ElementAt(0).ToString());
                    

                    for (int k = 1; k <= AuthNum; k++)
                    {
                        if (k == 1)
                        {

                            if (ID != null
                                       && (this.isTokenSequenceIllegal(int.Parse(LaneID[5].ToString()), ID, CSID, ref s) == false)
                                       && (this.isFirstVehicleInLane(int.Parse(LaneID[5].ToString()), ID, CSID) == true))
                            {


                                for (int i = 1; i <= svmp.CS_Count; i++)
                                {
                                    CSID = int.Parse(svmp.SectionID.ElementAt(i - 1).ToString());
                                    IsAuth[CSID] = true;

                                   
                                    if (this.Authorize_CS_to_Vehicle.Keys.Contains(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())))      //将车辆的CSID和ID添加到 Authorize_CS_to_Vehicle
                                    {
                                        this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                        //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除

                                        //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                        //xc
                                        Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                        string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                        int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                        int temp = int.Parse(svmp.SectionID.ElementAt(i - 1).ToString());
                                        Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[temp].ElementAt(0));
                                        string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                        int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());

                                        if (LaneIDtemp1 != LaneIDtemp2)
                                        {
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Remove(ID);
                                        }

                                        //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[int.Parse()].ElementAt(0).ElementAt(0))
                                        //{
                                        //    this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Remove(ID);
                                        //}


                                    }
                                    else
                                    {
                                        //
                                        this.Authorize_CS_to_Vehicle.Add(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()), null);
                                        this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())] = new List<string>();     //可以值是null，用的时候在实例化。
                                        this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                    }



                                    if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)   //不会死锁
                                    {
                                        this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()),Intersection);
                                        this.setToken(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()), ID);

                                        Debug.WriteLine("HWFP-SQ-SV" + "\t" + "有HM" + "\t" + AuthNum);
                                    }
                                    else    //会产生死锁   第一辆车不授权，后面的车辆更不授权。
                                    {
                                        this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Remove(ID);
                                        //如果SCID所对应的 list的数量为0，说明 此临界区对应的队列 为空。没有车辆了 
                                        if (this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Count == 0)
                                        {
                                            this.Authorize_CS_to_Vehicle.Remove(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()));
                                            break;
                                        }
                                        break;
                                    }

                                }


                                //判断当前被授权车辆是否还有未申请的临界区
                                SuperVehicleManager stmp = null;
                                int kkkk = 0;
                                for (int i1 = 1; i1 < 5; ++i1)
                                {
                                    for (int j = 0; j < this.LaneQueue[i1].Count; ++j)
                                    {
                                        if (this.LaneQueue[i1].ElementAt(j).ID == ID)
                                        {
                                            stmp = this.LaneQueue[i1].ElementAt(j);
                                            for (kkkk = 0; kkkk < stmp.CS_Count; kkkk++)
                                            {
                                                if (stmp.Token[int.Parse(stmp.SectionID[kkkk].ToString())] == false)
                                                {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }

                                //若车辆未申请完成所有临界区，则将其存入Authorized_Vehicle_Sequence中，作为当前仍需申请临界区的车辆对待
                                if (kkkk != svmp.CS_Count)
                                {
                                    if (stmp != null)
                                    {
                                        bool mark = false;
                                        for (int k1 = 0; k1 < this.Authorized_Vehicle_Sequence.Count; k1++)
                                        {
                                            if (this.Authorized_Vehicle_Sequence[k1] == stmp.ID)
                                            {
                                                mark = true;
                                            }
                                        }
                                        if (mark == false)
                                        {
                                            this.Authorized_Vehicle_Sequence.Add(stmp.ID);
                                        }
                                    }
                                }
                                else
                                {//该车辆已经申请完成所有的临界区，无需再次判断

                                    bool mark = false;
                                    for (int k1 = 0; k1 < this.Authorized_Vehicle_Sequence.Count; k1++)
                                    {
                                        if (this.Authorized_Vehicle_Sequence[k1] == stmp.ID)
                                        {
                                            mark = true;
                                        }
                                    }
                                    if (mark == false)
                                    {
                                        this.Authorized_Vehicle_Sequence.Add(stmp.ID);
                                    }
                                    this.Already_Authorized_All_CS_Vehicles.Add(stmp.ID);

                                }
                            }

                        }
                        else            // k!=1 , 后面的车辆
                        {

                            ID0 = ID;

                            //被选中车辆的ID
                            Vehicle vetemp = CarInLaneNext(ID0);
                            ID = vetemp.Get_ID();
                            LaneID = FindVehicleByID(ID).Get_Current_LaneID();


                            if (ID != ID0)
                            {
                                //continue;
                            }
                            else
                            {
                                break;
                            }


                            for (int i = 1; i <= 4; i++)
                            {
                                foreach (SuperVehicleManager svmpl in LaneQueue[i])
                                {
                                    if (ID == svmpl.getID())
                                    {
                                        svmplater = svmpl;
                                    }
                                }
                            }

                            CSID = int.Parse(svmplater.SectionID.ElementAt(0).ToString());

                            if (ID != null
                                    && (this.isTokenSequenceIllegal(int.Parse(LaneID[5].ToString()), ID, CSID, ref s) == false))                         
                            {


                                for (int i = 1; i <= svmplater.CS_Count; i++)
                                {
                                    CSID = int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString());
                                    IsAuth[CSID] = true;

                                    if (this.Authorize_CS_to_Vehicle.Keys.Contains(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())))      //将车辆的CSID和ID添加到 Authorize_CS_to_Vehicle
                                    {
                                        this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                    }
                                    else
                                    {
                                        //
                                        this.Authorize_CS_to_Vehicle.Add(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()), null);
                                        this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())] = new List<string>();     //可以值是null，用的时候在实例化。
                                        this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                    }

                                    if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)   //不会死锁
                                    {
                                        this.sendMessage(Definitions.MsgAuthorize, ID, svmplater.Original_Priority, int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()),Intersection);
                                        this.setToken(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()), ID);
                                    }
                                    else    //会产生死锁   第一辆车不授权，后面的车辆更不授权。
                                    {
                                        this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Remove(ID);

                                        if (this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Count == 0)
                                        {
                                            this.Authorize_CS_to_Vehicle.Remove(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()));
                                            break;
                                        }
                                        break;
                                    }
                                    Time = svmplater.Te[svmplater.CS_Count];
                                    StartTime = svmplater.Ts[1];
                                    SVMP = svmplater;

                                }


                                //判断当前被授权车辆是否还有未申请的临界区
                                SuperVehicleManager stmp = null;
                                int kkkk = 0;
                                for (int i1 = 1; i1 < 5; ++i1)
                                {
                                    for (int j = 0; j < this.LaneQueue[i1].Count; ++j)
                                    {
                                        if (this.LaneQueue[i1].ElementAt(j).ID == ID)
                                        {
                                            stmp = this.LaneQueue[i1].ElementAt(j);
                                            for (kkkk = 0; kkkk < stmp.CS_Count; kkkk++)
                                            {
                                                if (stmp.Token[int.Parse(stmp.SectionID[kkkk].ToString())] == false)
                                                {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }

                                //若车辆未申请完成所有临界区，则将其存入Authorized_Vehicle_Sequence中，作为当前仍需申请临界区的车辆对待
                                if (kkkk != svmplater.CS_Count)
                                {
                                    if (stmp != null)
                                    {
                                        bool mark = false;
                                        for (int k1 = 0; k1 < this.Authorized_Vehicle_Sequence.Count; k1++)
                                        {
                                            if (this.Authorized_Vehicle_Sequence[k1] == stmp.ID)
                                            {
                                                mark = true;
                                            }
                                        }
                                        if (mark == false)
                                        {
                                            this.Authorized_Vehicle_Sequence.Add(stmp.ID);
                                        }
                                    }
                                }
                                else
                                {//该车辆已经申请完成所有的临界区，无需再次判断

                                    bool mark = false;
                                    for (int k1 = 0; k1 < this.Authorized_Vehicle_Sequence.Count; k1++)
                                    {
                                        if (this.Authorized_Vehicle_Sequence[k1] == stmp.ID)
                                        {
                                            mark = true;
                                        }
                                    }
                                    if (mark == false)
                                    {
                                        this.Authorized_Vehicle_Sequence.Add(stmp.ID);
                                    }
                                    this.Already_Authorized_All_CS_Vehicles.Add(stmp.ID);

                                }
                            }
                        }

                    }

                }




                //前面是单车道的多车授权，后面开始写其他车道的单车授权了
                if (SVMP.Left[int.Parse(SVMP.Original_SectionID.ElementAt(SVMP.CS_Count - 1).ToString())] == true)  //用来标记 主干道多车授权的最后一辆车是否离开其所需要的最后一个临界区 true 为离开，false为未离开
                {
                    IsPass = true;
                }


                bool FlagOther = false;
                while (Authorize_CS_to_Vehicle.Count <= 3 && Authorize_CS_to_Vehicle.Count > 0 && !IsPass)   //&&  Main.getGlobalTime() < StartTime
                {

                    //次干道上的车辆单次授权
                    for (int b = 1; b <= this.MaxAuthNum / 4; b++)
                    {

                        if (Authorize_CS_to_Vehicle.Count == 3)
                        {
                            SuperVehicleManager svmpauththree = null;
                            svmpauththree = GetOneEmptyCSCar();
                            if (svmpauththree == null)
                            {
                                FlagOther = true;
                                break;
                            }
                            if (svmpauththree != null && svmpauththree.Te[svmpauththree.CS_Count] > SVMP.Te[SVMP.CS_Count])//-0.5  //SVMP.Te[SVMP.CS_Count]---<<< Time
                            {
                                FlagOther = true;
                                break;
                            }
                            CSID = int.Parse(svmpauththree.SectionID.ElementAt(0).ToString());
                            ID = svmpauththree.getID();
                            if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                            {
                                Authorize_CS_to_Vehicle.Add(CSID, null);
                                Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                Authorize_CS_to_Vehicle[CSID].Add(ID);
                            }
                            else
                            {
                                if (!Authorize_CS_to_Vehicle[CSID].Contains(ID))
                                {
                                    Authorize_CS_to_Vehicle[CSID].Add(ID);
                                }


                                //xc
                                Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[CSID].ElementAt(0));
                                string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());
                                                                                               
                                if (LaneIDtemp1 != LaneIDtemp2)
                                //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[CSID].ElementAt(0).ElementAt(0))
                                {
                                    this.Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                }

                            }
                            if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                            {
                                this.sendMessage(Definitions.MsgAuthorize, ID, svmpauththree.Original_Priority, CSID, Intersection);
                                IsAuth[CSID] = true;
                                this.setToken(CSID, ID);
                            }
                            else
                            {
                                Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                {
                                    Authorize_CS_to_Vehicle.Remove(CSID);
                                }
                            }
                            this.AddCarInAuthList(svmpauththree);

                        }
                        else if (Authorize_CS_to_Vehicle.Count == 2)
                        {
                            SuperVehicleManager svmpauthtwo = null;
                            svmpauthtwo = GetTwoEmptyCSCar();
                            if (svmpauthtwo == null)
                            {
                                FlagOther = true;
                                break;
                            }
                            if (svmpauthtwo != null && svmpauthtwo.Te[svmpauthtwo.CS_Count] > SVMP.Te[SVMP.CS_Count]) //-0.5
                            {
                                FlagOther = true;
                                break;
                            }
                            if (svmpauthtwo.CS_Count == 1)
                            {
                                CSID = int.Parse(svmpauthtwo.SectionID.ElementAt(0).ToString());
                                ID = svmpauthtwo.getID();
                                if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                {
                                    Authorize_CS_to_Vehicle.Add(CSID, null);
                                    Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                    Authorize_CS_to_Vehicle[CSID].Add(ID);
                                }
                                else
                                {
                                    if (!Authorize_CS_to_Vehicle[CSID].Contains(ID))
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }


                                    //XC
                                    //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                    //xc
                                    Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                    string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                    int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                    Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[CSID].ElementAt(0));
                                    string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                    int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());


                                    //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                    //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[CSID].ElementAt(0).ElementAt(0))
                                    if (LaneIDtemp1 != LaneIDtemp2)

                                    //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[CSID].ElementAt(0).ElementAt(0))
                                    {
                                        this.Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                    }



                                }
                                if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                {
                                    this.sendMessage(Definitions.MsgAuthorize, ID, svmpauthtwo.Original_Priority, CSID, Intersection);
                                    IsAuth[CSID] = true;
                                    this.setToken(CSID, ID);
                                }
                                else
                                {
                                    Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                    if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                    {
                                        Authorize_CS_to_Vehicle.Remove(CSID);
                                    }
                                }
                                this.AddCarInAuthList(svmpauthtwo);
                            }
                            else
                            {

                                for (int q = 1; q <= 2; q++)
                                {
                                    CSID = int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString());
                                    ID = svmpauthtwo.getID();
                                    if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                    {
                                        Authorize_CS_to_Vehicle.Add(CSID, null);
                                        Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    else
                                    {
                                        if (!Authorize_CS_to_Vehicle[CSID].Contains(ID))
                                        {
                                            Authorize_CS_to_Vehicle[CSID].Add(ID);
                                        }

                                        //xc
                                        Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                        string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                        int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                        int temp = int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString());
                                        Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[temp].ElementAt(0));
                                        string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                        int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());


                                        //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                        //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString())].ElementAt(0).ElementAt(0))
                                        if (LaneIDtemp1 != LaneIDtemp2)

                                        //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                        //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString())].ElementAt(0).ElementAt(0))
                                        {
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString())].Remove(ID);
                                            if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                            {
                                                Authorize_CS_to_Vehicle.Remove(CSID);
                                            }
                                            for (int w = 1; w <= 4; w++)
                                            {
                                                foreach (string str in Authorize_CS_to_Vehicle[w])
                                                {
                                                    if (str == ID)
                                                    {
                                                        Authorize_CS_to_Vehicle[w].Remove(ID);
                                                        if (Authorize_CS_to_Vehicle[w].Count == 0)
                                                        {
                                                            Authorize_CS_to_Vehicle.Remove(w);
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                    if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                    {
                                        this.sendMessage(Definitions.MsgAuthorize, ID, svmpauthtwo.Original_Priority, CSID, Intersection);
                                        IsAuth[CSID] = true;
                                        this.setToken(CSID, ID);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                        {
                                            Authorize_CS_to_Vehicle.Remove(CSID);
                                        }


                                        for (int w = 1; w <= 4; w++)
                                        {
                                            foreach (string str in Authorize_CS_to_Vehicle[w])
                                            {
                                                if (str == ID)
                                                {
                                                    Authorize_CS_to_Vehicle[w].Remove(ID);
                                                    if (Authorize_CS_to_Vehicle[w].Count == 0)
                                                    {
                                                        Authorize_CS_to_Vehicle.Remove(w);
                                                    }
                                                }
                                            }
                                        }


                                    }
                                }
                                this.AddCarInAuthList(svmpauthtwo);

                            }

                        }
                        else if (Authorize_CS_to_Vehicle.Count == 1)
                        {
                            SuperVehicleManager svmpauthone = null;
                            svmpauthone = GetThreeEmptyCSCar();
                            if (svmpauthone == null)
                            {
                                FlagOther = true;
                                break;
                            }
                            if (svmpauthone != null && svmpauthone.Te[svmpauthone.CS_Count] > SVMP.Te[SVMP.CS_Count])  //-0.5
                            {
                                FlagOther = true;
                                break;
                            }
                            if (svmpauthone.CS_Count == 1)
                            {
                                CSID = int.Parse(svmpauthone.SectionID.ElementAt(0).ToString());
                                ID = svmpauthone.getID();
                                if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                {
                                    Authorize_CS_to_Vehicle.Add(CSID, null);
                                    Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                    Authorize_CS_to_Vehicle[CSID].Add(ID);
                                }
                                else
                                {
                                    if (!Authorize_CS_to_Vehicle[CSID].Contains(ID))
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }

                                    //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                    //xc
                                    Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                    string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                    int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                    Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[CSID].ElementAt(0));
                                    string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                    int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());


                                    if (LaneIDtemp1 != LaneIDtemp2)
                                    //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[CSID].ElementAt(0).ElementAt(0))
                                    {
                                        this.Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                    }
                                }
                                if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                {
                                    this.sendMessage(Definitions.MsgAuthorize, ID, svmpauthone.Original_Priority, CSID, Intersection);
                                    IsAuth[CSID] = true;
                                    this.setToken(CSID, ID);
                                }
                                else
                                {
                                    Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                    if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                    {
                                        Authorize_CS_to_Vehicle.Remove(CSID);

                                        if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                        {
                                            Authorize_CS_to_Vehicle.Remove(CSID);
                                        }


                                        for (int w = 1; w <= 4; w++)
                                        {
                                            foreach (string str in Authorize_CS_to_Vehicle[w])
                                            {
                                                if (str == ID)
                                                {
                                                    Authorize_CS_to_Vehicle[w].Remove(ID);
                                                    if (Authorize_CS_to_Vehicle[w].Count == 0)
                                                    {
                                                        Authorize_CS_to_Vehicle.Remove(w);
                                                    }
                                                }
                                            }
                                        }


                                    }
                                }
                                this.AddCarInAuthList(svmpauthone);
                            }
                            else
                            {

                                for (int q = 1; q <= svmpauthone.CS_Count; q++)
                                {
                                    CSID = int.Parse(svmpauthone.SectionID.ElementAt(q - 1).ToString());
                                    ID = svmpauthone.getID();
                                    if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                    {
                                        Authorize_CS_to_Vehicle.Add(CSID, null);
                                        Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    else
                                    {
                                        if (!Authorize_CS_to_Vehicle[CSID].Contains(ID))
                                        {
                                            Authorize_CS_to_Vehicle[CSID].Add(ID);
                                        }
                                        //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除

                                        //xc
                                        Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                        string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                        int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                        int temp = int.Parse(svmpauthone.SectionID.ElementAt(q - 1).ToString());
                                        Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[temp].ElementAt(0));
                                        string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                        int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());


                                        //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除
                                        //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString())].ElementAt(0).ElementAt(0))
                                        if (LaneIDtemp1 != LaneIDtemp2)

                                        //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[int.Parse()].ElementAt(0).ElementAt(0))
                                        {
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmpauthone.SectionID.ElementAt(q - 1).ToString())].Remove(ID);

                                            if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                            {
                                                Authorize_CS_to_Vehicle.Remove(CSID);
                                            }


                                            for (int w = 1; w <= 4; w++)
                                            {
                                                foreach (string str in Authorize_CS_to_Vehicle[w])
                                                {
                                                    if (str == ID)
                                                    {
                                                        Authorize_CS_to_Vehicle[w].Remove(ID);
                                                        if (Authorize_CS_to_Vehicle[w].Count == 0)
                                                        {
                                                            Authorize_CS_to_Vehicle.Remove(w);
                                                        }
                                                    }
                                                }
                                            }



                                        }
                                    }
                                    if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                    {
                                        this.sendMessage(Definitions.MsgAuthorize, ID, svmpauthone.Original_Priority, CSID, Intersection);
                                        IsAuth[CSID] = true;
                                        this.setToken(CSID, ID);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                        {
                                            Authorize_CS_to_Vehicle.Remove(CSID);

                                            if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                            {
                                                Authorize_CS_to_Vehicle.Remove(CSID);
                                            }


                                            for (int w = 1; w <= 4; w++)
                                            {
                                                foreach (string str in Authorize_CS_to_Vehicle[w])
                                                {
                                                    if (str == ID)
                                                    {
                                                        Authorize_CS_to_Vehicle[w].Remove(ID);
                                                        if (Authorize_CS_to_Vehicle[w].Count == 0)
                                                        {
                                                            Authorize_CS_to_Vehicle.Remove(w);
                                                        }
                                                    }
                                                }
                                            }



                                        }
                                    }
                                }
                                this.AddCarInAuthList(svmpauthone);
                            }

                        }


                    }

                    if (FlagOther == true)
                    {
                        break;
                    }

                }
                //其他车道的单车授权了  完


            }


        }

        /************************************************************************/
        /*                                                                     */
        /************************************************************************/

        private double WaitTime(int n)
        {
            SuperVehicleManager svmp = null;
            for (int i = 0; i < LaneQueue[n].Count(); i++)
            {
                svmp = LaneQueue[n].ElementAt(i);
                if (svmp.Original_Priority == Definitions.Prio_High)
                {

                }
                else if (svmp.Original_Priority == Definitions.Prio_Mid)
                {

                }

            }

            return 0.0;
        }




        /************************************************************************/
        /* 返回车道中 低优先级 车辆的个数                                                                     */
        /************************************************************************/
        private int LowCarNum(int n)
        {

            int Num = 0;

            for (int i = 0; i < LaneQueue[n].Count(); i++)
            {
                if (LaneQueue[n].ElementAt(i).Original_Priority == Definitions.Prio_Low)
                {
                    Num++;
                }

            }
            return Num;

        }

        /************************************************************************/
        /* 返回车道中 中优先级 车辆的个数                                                                     */
        /************************************************************************/
        private int MidCarNum(int n)
        {

            int Num = 0;

            for (int i = 0; i < LaneQueue[n].Count(); i++)
            {
                if (LaneQueue[n].ElementAt(i).Original_Priority == Definitions.Prio_Mid)
                {
                    Num++;
                }

            }
            return Num;

        }

        /************************************************************************/
        /* 返回车道中 高优先级 车辆的个数                                                                     */
        /************************************************************************/
        private int HighCarNum(int n)
        {

            int Num = 0;

            for (int i = 0; i < LaneQueue[n].Count(); i++)
            {
                if (LaneQueue[n].ElementAt(i).Original_Priority == Definitions.Prio_High)
                {
                    Num++;
                }

            }
            return Num;

        }


        /************************************************************************/
        /* 返回车道中第一辆高优先级车辆的前车个数
         * 若返回-1，则说明该车道中没有高优先级车辆的个数
         * 
         * 
         * n代表车道编号                                                                      */
        /************************************************************************/

        private int HighCarFrontNum(int n)
        {

            int Num = 0;
            for (int i = 0; i < LaneQueue[n].Count(); i++)
            {
                if (LaneQueue[n].ElementAt(i).Original_Priority == Definitions.Prio_High)
                {
                    Num = i;
                    return Num;
                }

            }
            return 0;
        }


        private float HighCarWaitTime(int n)
        {
            SuperVehicleManager svmp = null;
            float time = 99999F;
            for (int i = 0; i < LaneQueue[n].Count(); i++)
            {
                svmp = LaneQueue[n].ElementAt(i);
                if (LaneQueue[n].ElementAt(i).Original_Priority == Definitions.Prio_High)
                {
                    time = svmp.Ts[1] - Main.getGlobalTime();
                    return time;
                }
                else if (LaneQueue[n].ElementAt(i).Original_Priority == Definitions.Prio_Mid)
                {
                    time = svmp.Ts[1] - Main.getGlobalTime();
                    return time;
                }

            }

            return time;
        }


        /************************************************************************/
        /* 预约时间片的个数
         * 
         *                                                                       */
        /************************************************************************/
        private int ReservationMum(SuperVehicleManager svmp)
        {
            float time = 0;
            int NumResTime = 0;
            string id = svmp.getID();
            float reservationTime = ReservationTime(id);

            time = (Main.getGlobalTime() - reservationTime) / Main.TimeStep;
            NumResTime = (int)time;

            return NumResTime;
        }


        /************************************************************************/
        /* 得到某一辆车的预约时间
         * 
         *                                                                       */
        /************************************************************************/
        private float ReservationTime(string id)
        {
            Vehicle vmp = FindVehicleByID(id);
            return vmp.Get_TimeReservation();  
        }

        /************************************************************************/
        /* 得到某一c车道上所有车辆的等待时间片的个数之和
         * 
         *                                                                       */
        /**********************************************int**************************/
        private int ResTimeSum(int n)
        {
            int Sum = 0;
            for (int i = 0; i < LaneQueue[n].Count(); i++)
            {
                Sum = ReservationMum(LaneQueue[n].ElementAt(i)) + Sum;
            }

            return Sum;
        }


        /************************************************************************/
        /* 找到当只有一个空闲临界区的时候，只需占用此空闲临界区的车辆
         *                                                                       */
        /************************************************************************/
        private SuperVehicleManager GetOneEmptyCSCar()
        {
            SuperVehicleManager svmp = null;
            int EmptyCs = 0;     //记录空闲的临界区的csid 是几
            if (Authorize_CS_to_Vehicle.Count != 3)
            {
                return null;
            }

            for (int n = 1; n <= 4; n++)
            {
                if (IsAuth[n] == false)
                {
                    EmptyCs = n;
                    break;
                }
            }
            switch (EmptyCs)
            {
                case 1:
                    if (LaneQueue[3].Count >= 1)
                    {
                        svmp = LaneQueue[3].ElementAt(0);
                        if (svmp.CS_Count != 1)
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 2:
                    if (LaneQueue[2].Count >= 1)
                    {
                        svmp = LaneQueue[2].ElementAt(0);
                        if (svmp.CS_Count != 1)
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 3:
                    if (LaneQueue[1].Count >= 1)
                    {
                        svmp = LaneQueue[1].ElementAt(0);
                        if (svmp.CS_Count != 1)
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 4:
                    if (LaneQueue[4].Count >= 1)
                    {
                        svmp = LaneQueue[4].ElementAt(0);
                        if (svmp.CS_Count != 1)
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                default:
                    return null;
            }
            return svmp;
        }

        /************************************************************************/
        /* 找到当只有两个空闲临界区的时候，只需占用此空闲临界区的车辆
         *                                                                       */
        /************************************************************************/
        private SuperVehicleManager GetTwoEmptyCSCar()
        {
            SuperVehicleManager svmp = null;
            SuperVehicleManager[] svmpshuzu = new SuperVehicleManager[3];  //用来存放符合条件的两辆车
            int[] EmptyCs = new int[3];     //记录空闲的临界区的csid 是几
            for (int q = 0; q < 3; q++)     //初始化
            {
                EmptyCs[q] = 0;
            }
            if (Authorize_CS_to_Vehicle.Count != 2)
            {
                return null;
            }
            int n = 1;
            int j = 1;
            for (n = 1; n <= 4; n++)
            {
                if (IsAuth[n] == false)
                {
                    EmptyCs[j] = n;
                    j++;
                }
            }

            int Sum = 0;
            for (int m = 1; m < j; m++)
            {
                Sum += EmptyCs[m];   //Sum为空闲临界区之和
            }

            int i = 1;
            switch (Sum)
            {


                case 5:
                    if (EmptyCs[1] == 1 && EmptyCs[2] == 4)
                    {
                        if ((LaneQueue[3].Count >= 1) || (LaneQueue[4].Count >= 1))
                        {

                            if (LaneQueue[3].Count != 0)
                            {
                                if (LaneQueue[3].ElementAt(0).CS_Count <= 1)
                                {
                                    svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                    i++;
                                }
                            }
                            if (LaneQueue[4].Count != 0)
                            {
                                if (LaneQueue[4].ElementAt(0).CS_Count <= 1)
                                {
                                    svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                    i++;
                                }
                            }
                        }
                        else
                        {
                            return null;
                        }
                        break;
                    }
                    else
                    {
                        if ((LaneQueue[1].Count >= 1) || (LaneQueue[2].Count >= 1))
                        {
                            if (LaneQueue[1].Count != 0)
                            {
                                if (LaneQueue[1].ElementAt(0).CS_Count <= 1)
                                {
                                    svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                    i++;
                                }
                            }
                            if (LaneQueue[2].Count != 0)
                            {
                                if (LaneQueue[2].ElementAt(0).CS_Count <= 1)
                                {
                                    svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                    i++;
                                }
                            }
                        }
                        else
                        {
                            return null;
                        }
                        break;
                    }

                case 3:
                    if ((LaneQueue[2].Count >= 1) || (LaneQueue[3].Count >= 1))
                    {
                        if (LaneQueue[2].Count != 0)
                        {
                            if (LaneQueue[2].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[3].Count != 0)
                        {
                            if (LaneQueue[3].ElementAt(0).CS_Count <= 1)
                            {
                                svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                i++;
                            }
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 4:
                    if ((LaneQueue[3].Count >= 1) || (LaneQueue[1].Count >= 1))
                    {
                        if (LaneQueue[3].Count != 0)
                        {
                            if (LaneQueue[3].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[1].Count != 0)
                        {
                            if (LaneQueue[1].ElementAt(0).CS_Count <= 1)
                            {
                                svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                i++;
                            }
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 7:
                    if ((LaneQueue[1].Count >= 1) || (LaneQueue[4].Count >= 1))
                    {
                        if (LaneQueue[1].Count != 0)
                        {
                            if (LaneQueue[1].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[4].Count != 0)
                        {
                            if (LaneQueue[4].ElementAt(0).CS_Count <= 1)
                            {
                                svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                i++;
                            }
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 6:
                    if ((LaneQueue[4].Count >= 1) || (LaneQueue[2].Count >= 1))
                    {
                        if (LaneQueue[4].Count != 0)
                        {
                            if (LaneQueue[4].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[2].Count != 0)
                        {
                            if (LaneQueue[2].ElementAt(0).CS_Count <= 1)
                            {
                                svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                i++;
                            }
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                default:
                    return null;
                    //MessageBox.Show(" GetTwoEmptyCSCar()  error!");                 
            }

            if (i == 3)          //说明找到2辆车
            {
                if (svmpshuzu[1].Original_Priority > svmpshuzu[2].Original_Priority)
                {
                    svmp = svmpshuzu[1];
                }
                else if (svmpshuzu[1].Original_Priority == svmpshuzu[2].Original_Priority)
                {
                    if (svmpshuzu[1].Ts[1] < svmpshuzu[2].Ts[1])
                    {
                        svmp = svmpshuzu[1];
                    }
                    else
                    {
                        svmp = svmpshuzu[2];
                    }
                }
                else
                {
                    svmp = svmpshuzu[2];
                }
            }
            else if (i == 2)     //说明找到1辆车
            {
                svmp = svmpshuzu[1];
            }
            else if (i == 1)     //说明找到0辆车
            {
                return null;
            }

            return svmp;
        }


        /************************************************************************/
        /* 找到当只有三个空闲临界区的时候，只需占用此空闲临界区的车辆
         *                                                                       */
        /************************************************************************/
        private SuperVehicleManager GetThreeEmptyCSCar()
        {
            SuperVehicleManager svmp = null;
            SuperVehicleManager[] svmpshuzu = new SuperVehicleManager[4];  //用来存放符合条件的两辆车
            int[] EmptyCs = new int[4];     //记录空闲的临界区的csid 是几
            for (int q = 0; q < 4; q++)     //初始化
            {
                EmptyCs[q] = 0;
            }
            if (Authorize_CS_to_Vehicle.Count != 1)
            {
                return null;
            }
            int n = 1;
            int j = 1;
            for (n = 1; n <= 4; n++)
            {
                if (IsAuth[n] == false)
                {

                    EmptyCs[j] = n;
                    j++;


                }
            }

            int Sum = 0;
            for (int m = 1; m < j; m++)
            {
                Sum += EmptyCs[m];
            }

            int i = 1;
            switch (Sum)
            {
                case 0:
                    return null;                  
                case 9:
                    if ((LaneQueue[1].Count >= 1) || (LaneQueue[4].Count >= 1) || (LaneQueue[2].Count >= 1))
                    {
                        if (LaneQueue[1].Count != 0)
                        {
                            if (LaneQueue[1].ElementAt(0).CS_Count <= 3)
                            {
                                svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[4].Count != 0)
                        {
                            if (LaneQueue[4].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[2].Count != 0)
                        {
                            if (LaneQueue[2].ElementAt(0).CS_Count == 1)
                            {
                                svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                i++;
                            }
                        }

                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 8:
                    if ((LaneQueue[3].Count >= 1) || (LaneQueue[1].Count >= 1) || (LaneQueue[4].Count >= 1))
                    {
                        if (LaneQueue[3].Count != 0)
                        {
                            if (LaneQueue[3].ElementAt(0).CS_Count <= 3)
                            {
                                svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[1].Count != 0)
                        {
                            if (LaneQueue[1].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[4].Count != 0)
                        {
                            if (LaneQueue[4].ElementAt(0).CS_Count == 1)
                            {
                                svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                i++;
                            }
                        }

                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 7:
                    if ((LaneQueue[4].Count >= 1) || (LaneQueue[2].Count >= 1) || (LaneQueue[3].Count >= 1))
                    {

                        if (LaneQueue[4].Count != 0)
                        {
                            if (LaneQueue[4].ElementAt(0).CS_Count <= 3)
                            {
                                svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[2].Count != 0)
                        {
                            if (LaneQueue[2].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[3].Count != 0)
                        {
                            if (LaneQueue[3].ElementAt(0).CS_Count == 1)
                            {
                                svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                i++;
                            }
                        }

                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 6:
                    if ((LaneQueue[2].Count >= 1) || (LaneQueue[3].Count >= 1) || (LaneQueue[1].Count >= 1))
                    {
                        if (LaneQueue[2].Count != 0)
                        {
                            if (LaneQueue[2].ElementAt(0).CS_Count <= 3)
                            {
                                svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[3].Count != 0)
                        {
                            if (LaneQueue[3].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[1].Count != 0)
                        {
                            if (LaneQueue[1].ElementAt(0).CS_Count == 1)
                            {
                                svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                i++;
                            }
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                default:
                    return null;
            }


            if (i == 4)                   //说明找到3辆车
            {
                int highcarnum = 0;
                int midcarnum = 0;
                int lowcarnum = 0;
                for (int e = 1; e < 4; e++)
                {
                    if (svmpshuzu[e].Original_Priority == Definitions.Prio_High)
                    {
                        highcarnum++;
                    }
                }
                for (int e = 1; e < 4; e++)
                {
                    if (svmpshuzu[e].Original_Priority == Definitions.Prio_Mid)
                    {
                        midcarnum++;
                    }
                }
                for (int e = 1; e < 4; e++)
                {
                    if (svmpshuzu[e].Original_Priority == Definitions.Prio_Low)
                    {
                        lowcarnum++;
                    }
                }


                if (highcarnum == 3 || midcarnum == 3 || lowcarnum == 3)//优先级相同时，找到最早到的
                {
                    int min = 1;
                    for (int w = 2; w < 4; w++)
                    {
                        if (svmpshuzu[w].Ts[1] < svmpshuzu[min].Ts[1])
                        {
                            min = w;
                        }
                    }
                    svmp = svmpshuzu[min];
                }
                else if (highcarnum == 2)
                {

                    int q = 1;
                    SuperVehicleManager[] svmpsz = new SuperVehicleManager[3];  //用来存放高优先级的的两辆车
                    for (int w = 1; w < 4; w++)
                    {
                        if (svmpshuzu[w].Original_Priority == Definitions.Prio_High)
                        {
                            svmpsz[q] = svmpshuzu[w];
                            q++;
                        }
                    }
                    if (q == 3)//说明把高优先级的两辆车放到数组中了
                    {
                        if (svmpsz[1].Ts[1] < svmpsz[2].Ts[1])
                        {
                            svmp = svmpsz[1];
                        }
                        else
                        {
                            svmp = svmpsz[2];
                        }
                    }

                }
                else if (highcarnum == 1)
                {
                    int flag = 0;
                    for (int w = 1; w < 4; w++)
                    {
                        if (svmpshuzu[w].Original_Priority == Definitions.Prio_High)
                        {
                            flag = w;
                        }
                    }
                    svmp = svmpshuzu[flag];
                }
                else if (highcarnum == 0 && midcarnum == 2)
                {

                    int q = 1;
                    SuperVehicleManager[] svmpsz = new SuperVehicleManager[3];  //用来存放中优先级的的两辆车
                    for (int w = 1; w < 4; w++)
                    {
                        if (svmpshuzu[w].Original_Priority == Definitions.Prio_Mid)
                        {
                            svmpsz[q] = svmpshuzu[w];
                            q++;
                        }
                    }
                    if (q == 3)//说明把高优先级的两辆车放到数组中了
                    {
                        if (svmpsz[1].Ts[1] < svmpsz[2].Ts[1])
                        {
                            svmp = svmpsz[1];
                        }
                        else
                        {
                            svmp = svmpsz[2];
                        }
                    }


                }
                else if (highcarnum == 0 && midcarnum == 1)
                {
                    int flag = 0;
                    for (int w = 1; w < 4; w++)
                    {
                        if (svmpshuzu[w].Original_Priority == Definitions.Prio_Mid)
                        {
                            flag = w;
                        }
                    }
                    svmp = svmpshuzu[flag];
                }


            }
            else if (i == 3)              //说明找到2辆车
            {
                if (svmpshuzu[1].Original_Priority > svmpshuzu[2].Original_Priority)
                {
                    svmp = svmpshuzu[1];
                }
                else if (svmpshuzu[1].Original_Priority == svmpshuzu[2].Original_Priority)
                {
                    if (svmpshuzu[1].Ts[1] < svmpshuzu[2].Ts[1])
                    {
                        svmp = svmpshuzu[1];
                    }
                    else
                    {
                        svmp = svmpshuzu[2];
                    }
                }
                else
                {
                    svmp = svmpshuzu[2];
                }
            }
            else if (i == 2)            //说明找到1辆车
            {
                svmp = svmpshuzu[1];
            }
            else if (i == 1)            //说明找到0辆车
            {
                return null;
            }

            return svmp;
        }

        /************************************************************************/
        /* 把已经全部授权车辆所需临界区的 车辆增加在 Already_Authorized_All_CS_Vehicles   */
        /************************************************************************/
        private void AddCarInAuthList(SuperVehicleManager svmp)
        {
            if (svmp.HaveTokenCount == svmp.CS_Count)
            {
                if (!this.Already_Authorized_All_CS_Vehicles.Contains(svmp.ID))
                {
                    this.Already_Authorized_All_CS_Vehicles.Add((svmp.ID));
                }
            }
        }

        //获取授权信息
        public Dictionary<int, List<string>> GetAuthorize_CS_to_Vehicle()
        {
            return this.Authorize_CS_to_Vehicle;
        }

        //根据ID在全局的VehicleList中找到Vehicle
        public static Vehicle FindVehicleByID(string ID)
        {
            Vehicle Vehicle = new Vehicle();
            for (int i = 0; i < MainData.Map.GlobalVehicleList.Count(); i++)
            {
                Vehicle veh = MainData.Map.GlobalVehicleList[i];
                if (veh.Get_ID() == ID)
                {
                    Vehicle = veh;
                }
            }
            return Vehicle;
        }

    }

}


